Ubuntu中Fortran进行数据可视化的常见方法
GNUplot是Fortran常用的外部绘图工具,适合生成简单的线图、散点图等。
sudo apt-get update && sudo apt-get install gnuplot
。data.f90
),通过open
语句将计算结果写入文本文件(如data.txt
)。示例代码:program data
implicit none
integer :: i
open(unit=10, file='data.txt', status='replace')
do i = 1, 10
write(10, *) i, sin(i) ! 写入x(i)和y(sin(i))数据
end do
close(10)
end program data
gfortran -o data data.f90 && ./data
,生成data.txt
。gnuplot
,然后执行plot 'data.txt' using 1:2 with lines
(1:2
表示用第1列作为x轴、第2列作为y轴,with lines
表示用线条连接数据点)。PLplot是专门为科学可视化设计的Fortran/C库,支持2D/3D绘图,功能更强大。
sudo apt-get update && sudo apt-get install libplplot-dev
。plot_example.f90
,调用PLplot API绘制正弦曲线:program plot_example
use plplot
implicit none
integer :: ierror
call plinit(ierror) ! 初始化PLplot
if (ierror /= 0) then
print *, 'Error initializing PLplot'
stop
end if
call pltxy(1.0, sin(1.0), 0.0) ! 添加数据点(x=1.0, y=sin(1.0))
call pltxy(2.0, sin(2.0), 0.0)
call pltxy(3.0, sin(3.0), 0.0)
call pltlabel('X Axis', 'Y Axis', 'Sine Wave') ! 添加坐标轴标签和标题
call plttitle('Simple PLplot Example')
call pltgrid(.true.) ! 显示网格
call pltdraw() ! 渲染图形
call pltpause(10.0) ! 暂停10秒(方便查看)
call pltfin(ierror) ! 结束绘图
end program plot_example
gfortran -o plot_example plot_example.f90 -lplplot
,执行./plot_example
即可显示图形窗口。若需更复杂的图表(如交互式图、热力图),可借助Python的Matplotlib库,通过Fortran生成数据后调用Python脚本。
sudo apt-get update && sudo apt-get install python3 python3-pip && pip3 install matplotlib numpy
。write_data.f90
,将数据写入data.txt
(同方法1)。plot_script.py
,使用Matplotlib读取data.txt
并绘制折线图:import matplotlib.pyplot as plt
# 读取Fortran生成的data.txt
with open('data.txt', 'r') as file:
data = [float(line.strip()) for line in file]
# 绘制折线图
plt.plot(range(1, len(data)+1), data, marker='o')
plt.xlabel('Index')
plt.ylabel('sin(Index)')
plt.title('Data Visualization via Python+Matplotlib')
plt.grid(True)
plt.show()
gfortran -o write_data write_data.f90 && ./write_data && python3 plot_script.py
,即可显示交互式图表。