постройте на одном рисунке несколько строк из разных файлов данных с помощью python

#python #for-loop #matplotlib

#python #для цикла #matplotlib

Вопрос:

Я новичок в области построения на одном рисунке нескольких строк из разных файлов данных с помощью matplotlib на python. В настоящее время у меня есть следующий скрипт, который должен отображать столбцы 1 и 2 из файла ‘statistics_pa_f0_vs_n.dat’. Я хочу также иметь возможность отображать в одном и том же столбце рисунка 1 и 2 из файла ‘statistics_pa_f1_vs_n.dat’

 #--- 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()
  

Комментарии:

1. pandas позволяет легко читать файлы разных форматов. Также может использоваться для последующего построения графика.

Ответ №1:

Самый простой способ сделать это (без использования какого-либо внешнего пакета) — написать простой класс, который считывает файл. Затем вызовите class несколько раз.

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