如何在for循环中从文件中读取x和y时绘制多行?

2024-06-26 18:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个for循环,对于每个输入文件,我从文件中读取x和y,并将它们保存在单独的列表中,然后绘制一个图形。现在我想在一个绘图中绘制所有文件的x-y。问题是我在for循环中从我的文件中读取x和y,所以我必须绘制它们,然后转到下一个文件,否则我将丢失x和y,我不想将它们保存在另一个文件中,然后再一起绘制。有什么建议吗?如果有任何建议,我将不胜感激,因为这是我第一次使用matplotlib,而且我还是python新手。在

for f in os.listdir(Source):
x=[]
y=[]
file_name= f
print 'Processing file : ' + str (file_name)
pkl_file = open( os.path.join(Source,f) , 'rb' )
List=pickle.load(pkl_file)
pkl_file.close()
x = [dt.datetime.strptime(i[0],'%Y-%m-%d')for i in List ]
y = [i[1] for i in List]
maxRange=max(y)

if not maxRange >= 5 :
    print 'The word #' +str(file_name[0]) + ' has a frequency of ' +str(maxRange) + '.'
else :
    fig = plt.figure()
    plt.ylim(0,maxRange)
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    plt.gca().xaxis.set_major_locator(mdates.YearLocator())
    plt.plot(x, y , 'm')
    plt.xlabel('Time')
    plt.ylabel('Frequency')
    fig.savefig("Plots/"+ file_name[0] + '.pdf' )

Tags: 文件nameinsourceforos绘制plt
1条回答
网友
1楼 · 发布于 2024-06-26 18:10:54

给你。冒昧地提出了一些建议,尽管不是全部。在

fig = plt.figure()
maxRange = 0
for file_name in os.listdir(source):
    print 'Processing file : ' + str(file_name)
    with open(os.path.join(source,file_name), 'rb') as pkl_file:
        lst = pickle.load(pkl_file)
    x,y = zip(*[(dt.datetime.strptime(x_i,'%Y-%m-%d'), y_i) for (x_i, y_i) in lst])
    if max(y) < 5 :
        print 'The word #' +str(file_name[0]) + ' has a frequency of ' +str(maxRange) + '.'
    else :
        maxRange=max(maxRange, max(y))
        plt.plot(x, y , 'm')
plt.ylim(0,maxRange)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.xlabel('Time')
plt.ylabel('Frequency')
fig.savefig("Plots/allfiles.pdf")

相关问题 更多 >