以下是关于如何使用Python进行预处理并使用gnuplot绘图的方法。
变体1
第一种变体使用gnuplot的pm3d
绘图风格。这样可以很好地插值直方图数据,使图像看起来更加平滑。但是对于大型数据集可能会出现问题,具体取决于输出图像格式(参见变体2)。
Python脚本process.py
使用numpy.histogram2d
生成直方图,输出保存为gnuplot的nonuniform matrix
格式。
from __future__ import print_function
import numpy as np
import sys
M = np.loadtxt('datafile.dat', skiprows=1)
bins_x = 100
bins_y = 100
H, xedges, yedges = np.histogram2d(M[:,0], M[:,1], [bins_x, bins_y])
print(bins_x, end=' ')
np.savetxt(sys.stdout, xedges, newline=' ')
print()
for i in range(0, bins_y):
print(yedges[i], end=' ')
np.savetxt(sys.stdout, H[:,i], newline=' ')
print(H[-1,i])
print(yedges[-1], end=' ')
np.savetxt(sys.stdout, H[:,-1], newline=' ')
print(H[-1,-1])
要绘制图形,只需运行以下gnuplot脚本:
reset
set terminal pngcairo
set output 'test.png'
set autoscale xfix
set autoscale yfix
set xtics out
set ytics out
set pm3d map interpolate 2,2 corners2color c1
splot '< python process.py' nonuniform matrix t ''
变体2
第二种变体使用image
绘图风格,适用于大型数据集(大直方图尺寸),但不适合像100x100
矩阵这样的情况:
from __future__ import print_function
import numpy as np
import sys
M = np.loadtxt('datafile.dat', skiprows=1)
bins_x = 100
bins_y = 200
H, xedges, yedges = np.histogram2d(M[:,0], M[:,1], [bins_x, bins_y])
xedges = xedges[:-1] + 0.5*(xedges[1] - xedges[0])
yedges = yedges[:-1] + 0.5*(yedges[1] - yedges[0])
print(bins_x, end=' ')
np.savetxt(sys.stdout, xedges, newline=' ')
print()
for i in range(0, bins_y):
print(yedges[i], end=' ')
np.savetxt(sys.stdout, H[:,i], newline=' ')
print()
要绘制图形,只需运行以下gnuplot脚本:
reset
set terminal pngcairo
set output 'test2.png'
set autoscale xfix
set autoscale yfix
set xtics out
set ytics out
plot '< python process2.py' nonuniform matrix with image t ''
可能有一些地方需要改进(特别是在Python脚本中),但应该能够工作。我不会发布结果图片,因为它的数据点很少,看起来很丑 ;)
。
gnuplot
本身中创建密度分布,只能使用smooth kdensity
在1D中实现。如果你想用gnuplot绘制数据,你必须使用其他工具(例如Python)预处理数据。 - Christoph