Linux下Fortran数据可视化实用指南
一、常用方案与适用场景
二、快速上手示例
方案A 外部工具Gnuplot
program plot_example
implicit none
integer, parameter :: n = 100
real :: x(n), y(n)
integer :: i
do i = 1, n
x(i) = i*0.1
y(i) = sin(x(i))
end do
open(unit=10, file='data.txt', status='replace')
do i = 1, n
write(10,*) x(i), y(i)
end do
close(10)
end program plot_example
编译运行:gfortran plot_example.f90 -o plot_example && ./plot_example
2) Gnuplot绘图
gnuplot
set title "Sine Function"
set xlabel "x"; set ylabel "sin(x)"
plot "data.txt" with lines
说明:Gnuplot支持2D/3D、多种标注与多种输出格式,适合快速可视化与出版级图形。
方案B Fortran内嵌PGPLOT
program scatter_plot
implicit none
integer, parameter :: n = 100
real :: x(n), y(n)
integer :: i
do i = 1, n
x(i) = real(i)/n
y(i) = x(i)**2
end do
call pgbegin(0, '/XWINDOW', 1, 1) ! 使用X11窗口;无图形环境可改为文件设备
call pgsci(1)
call pgpt(n, x, y, 2) ! 绘制点
call pgend()
end program scatter_plot
编译(示例):gfortran scatter_plot.f90 -lpgplot -o scatter_plot
说明:PGPLOT为Fortran 77/C可调用库,支持多种设备(如X Windows、PostScript),适合科研成图。
方案C Web实时可视化
program heat_simulation
implicit none
integer, parameter :: n = 100
real :: temperature(n), dt = 0.01
integer :: i, step
temperature = 0.0
temperature(n/2) = 100.0
do step = 1, 1000
call simulate_heat_diffusion(temperature, dt)
print *, temperature ! 到STDOUT
call sleep(1)
end do
contains
subroutine simulate_heat_diffusion(temp, dt)
real, intent(inout) :: temp(:)
real, intent(in) :: dt
real :: new_temp(size(temp))
integer :: i
do i = 2, size(temp)-1
new_temp(i) = temp(i) + dt*(temp(i-1) - 2*temp(i) + temp(i+1))
end do
temp = new_temp
end subroutine
end program heat_simulation
gfortran -o heat_sim heat_simulation.f90
websocketd --port=8080 ./heat_sim
<!doctype html>
<meta charset="utf-8">
<canvas id="chart" width="800" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line', data: { labels: Array.from({length:100},(_,i)=>i), datasets:[{label:'T', data:[], borderColor:'red'}] }
});
const ws = new WebSocket('ws://localhost:8080/');
ws.onmessage = (e) => { chart.data.datasets[0].data = e.data.split(' ').map(parseFloat); chart.update(); };
</script>
说明:websocketd将任何使用STDIN/STDOUT的程序变为WebSocket服务,前端可实时绘图与交互。
三、方案对比与选型建议
| 方案 | 典型工具/库 | 优点 | 局限 | 适用场景 |
|---|---|---|---|---|
| 外部工具 | Gnuplot、PLplot(命令行/脚本) | 上手快、格式丰富、脚本化批量出图 | 需数据文件交换,交互性一般 | 科研绘图、论文成图 |
| Fortran内嵌库 | PGPLOT、PLplot、MathGL、DISLIN | 程序内控制、交互友好、便于自动化 | 需安装与链接库,学习API | 计算过程中动态可视化 |
| Web实时 | websocketd + 前端图表库 | 实时、跨平台、易分享 | 需前端开发,网络与序列化开销 | 长时模拟监控、远程展示 |
| 专用/高级 | NCAR Graphics、OpenDX、MayaVi | 专业能力强(等值线、地图投影、体渲染) | 学习曲线或部署复杂度较高 | 气象/海洋/三维场可视化 |
| 说明:表中工具均为Linux下常用选择,适配多数Fortran工作流。 |
四、实践建议