【发布时间】:2020-11-11 19:38:14
【问题描述】:
我是使用 python 中的 matplotlib 在同一图中绘制来自不同数据文件的多行的新手。目前我有以下脚本,用于从文件'statistics_paa_f0_vs_N.dat'中绘制第 1 列和第 2 列。我还希望能够从文件'statistics_paa_f1_vs_N.dat'中绘制相同的图列1和2
#--- Import the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np
#--- initiate the list of coordinates for x and y lists
x,y = [],[]
#--- iterate over each line of the file and store it as a string
for line in open('statistics_paa_f0_vs_N.dat','r'):
values = [float(s) for s in line.split()]
x.append(values[0])
y.append(values[1])
#--- plot the data
plt.plot(x,y,color='r',label='line1') # r - red colour
plt.xlabel('time (s)',fontsize=12)
plt.ylabel('Density (kg/m3)',fontsize=12)
plt.title('hi',fontsize=20,fontweight='bold')
plt.legend(loc='upper right')
plt.grid(False)
plt.axis(True)
#--- show and save the plot
plt.savefig('png_files-matplotlib/test.png')
plt.show()
【问题讨论】:
-
pandas使读取不同格式的文件变得非常容易。也可用于事后绘图。
标签: python for-loop matplotlib