我正在尝试用数据读取许多不同的文本文件,然后将数据绘制成图表。我的函数在读取数据时工作,我可以将其绘制成图形,但有一个小问题:当我运行程序时,它似乎用当前函数的数据覆盖了上一个函数调用的数据,从而创建了一个包含所有相同的数据。我已经验证了数据实际上是不同的,正如我在调用每个函数后调用 matplotlib 绘制数据并将其全部绘制在图 1 上时所看到的那样。然而,最后绘制的图 2 恰好产生了 4 条线相同。谁能指出为什么会发生这种情况以及如何缩短代码以便最后只调用一次 matplotlib 来绘制所有数据?可以在此处找到数据文件的 zip 文件,以便程序运行:
#import numpy as np
import matplotlib.pyplot as plt
flux = []
SEM = []
depth = []
c = 0
def data_reader(file_name, first_surface):
del flux[:]
del SEM[:]
del depth[:]
with open (file_name) as inf:
lines = inf.readlines()
for (i, line,) in enumerate(lines):
if ' surface %d' %first_surface in line:
data = (lines[i+1].strip())
fields = data.split()
numbers = list(map(float,fields))
flux.append(numbers[0])
SEM.append(numbers[1])
first_surface += 1
depth.append(first_surface - 101)
return (flux, SEM, first_surface)
data1 = data_reader('concrete_40billion.txt', 101)
flux_1 = data1[0]
SEM_1 = data1[1]
plt.figure(1)
plt.rcParams['legend.loc'] = 'best'
plt.autoscale(enable=True, axis='y', tight=None)
plt.autoscale(enable=True, axis='x', tight=None)
plt.plot(depth, flux_1, 'k')
plt.loglog()
plt.hold(True)
print('plots created')
plt.show()
data2 = data_reader('du_1m_20billion.txt', 101)
flux_2 = data2[0]
SEM_2 = data2[1]
plt.figure(1)
plt.rcParams['legend.loc'] = 'best'
plt.autoscale(enable=True, axis='y', tight=None)
plt.autoscale(enable=True, axis='x', tight=None)
plt.plot(depth, flux_2, 'g')
plt.loglog()
plt.hold(True)
print('plots created')
plt.show()
data3 = data_reader('du_2m_20billion.txt', 101)
flux_3 = data3[0]
SEM_3 = data3[1]
plt.figure(1)
plt.rcParams['legend.loc'] = 'best'
plt.autoscale(enable=True, axis='y', tight=None)
plt.autoscale(enable=True, axis='x', tight=None)
plt.plot(depth, flux_3, 'b')
plt.loglog()
plt.hold(True)
print('plots created')
plt.show()
data4 = data_reader('du_3cm_20billion.txt', 101)
flux_4 = data4[0]
SEM_4 = data4[1]
plt.figure(1)
plt.rcParams['legend.loc'] = 'best'
plt.autoscale(enable=True, axis='y', tight=None)
plt.autoscale(enable=True, axis='x', tight=None)
plt.plot(depth, flux_4, 'r')
plt.loglog()
plt.hold(True)
print('plots created')
plt.show()
#difference = [a - b for a,b in zip(flux_1, flux_2)]
#print difference
plt.rcParams['legend.loc'] = 'best'
plt.figure(2)
#plt.xlim(0, 0.04)
#plt.ylim(0, 7000)
plt.autoscale(enable=True, axis='y', tight=None)
plt.autoscale(enable=True, axis='x', tight=None)
plt.plot(depth, flux_1, 'k',label='flux 1')
plt.plot(depth, flux_2, 'g', label='flux 2')
plt.plot(depth, flux_3, 'b', label='flux 3')
plt.plot(depth, flux_4, 'r', label='flux 4')
plt.xlabel('Depth (cm)')
plt.ylabel('Flux (particles/cm^2*s)')
plt.loglog()
plt.legend()
print('plots created')
plt.show()