【问题标题】:plot in the same figure multiple lines from different data files with python使用python在同一图中绘制来自不同数据文件的多行
【发布时间】: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


【解决方案1】:

最简单的方法(不使用任何外部包)是编写一个读取文件的简单类。然后,多次调用类。

import matplotlib.pyplot as plt
import numpy as np


class ReadFile():

    def __init__(self,filename : str): 

        self.x = [] 
        self.y = []

        with open(filename,'r') as f:
            lines = f.readlines()
            for line in lines:
                val = [float(s) for s in line.split() ] 
                self.x.append(val[0])
                self.y.append(val[1])

        self.x = np.array(self.x,dtype=np.double)
        self.y = np.array(self.y,dtype=np.double)

    def getData(self):
        return self.x, self.y



file1 = ReadFile("./test")
file2 = ReadFile("./test1")

plt.plot(*file1.getData(), linewidth = 3.0, label = "test ")
plt.plot(*file2.getData(), linewidth = 3.0, label = "test1")


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.show()

【讨论】:

    【解决方案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,z,e,l,m = [],[],[],[],[],[]
    #--- 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])
    
    for line in open('statistics_paa_f1_vs_N.dat','r'):
        values = [float(s) for s in line.split()]
        e.append(values[0])
        z.append(values[1])
    
    for line in open('statistics_paa_f5_vs_N.dat','r'):
        values = [float(s) for s in line.split()]
        l.append(values[0])
        m.append(values[1])
    
    #--- plot the data
    plt.plot(x,y,'rs:',label='f=0')
    plt.plot(e,z,'gs:',label='f=1')
    plt.plot(l,m,'bs:',label='f=0.5')
    #plt.plot(x,y,x,z,color='r',label='line1') # r - red colour
    plt.xlabel('N (mer)',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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多