假设, 我有一些数据点定义了5个不同的图形,如下图所示。
如何在y轴的值上绘制这些的平均图表?
我不能直接这样做,因为不同图形的数据点在x轴上的值不同。
答案 0 :(得分:0)
import numpy as np
def line_tuple(filename,cols=(0,1)):
return np.loadtxt(filename,usecols=cols,unpack=True)
#parse each line from the datafile into a tuple of the form (xvals,yvals)
#store that tuple in a list.
data = [line_tuple(fname) for fname in ("line1.txt","line2.txt","line3.txt","line4.txt","line5.txt")]
#This is the minimum and maximum from all the datapoints.
xmin = min(line[0].min() for line in data)
xmax = max(line[0].max() for line in data)
#100 points evenly spaced along the x axis
x_points = np.linspace(xmin,xmax,100)
#interpolate your values to the evenly spaced points.
interpolated = [np.interp(x_points,d[0],d[1]) for d in data]
#Now do the averaging.
averages = [np.average(x) for x in zip(*interpolated)]
#put the average value along with it's x point into a file.
with open('outfile','w') as fout:
for x,avg in zip(x_points,averages):
fout.write('{0} {1}\n'.format(x,avg))
现在我绘制它:
plot 'line1.txt' w l, \
'line2.txt' w l, \
'line3.txt' w l, \
'line4.txt' w l, \
'line5.txt' w l, \
'outfile' w l