0

I am new into the field of plotting in the same figure multiple lines from different data files with matplotlib in python. Currently I have the following script which is to plot column 1 and 2 from file 'statistics_paa_f0_vs_N.dat'. I want to be able also to plot in the same figure column 1 and 2 from file 'statistics_paa_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 makes it really easy to read in files of different formats. Can also be used for plotting afterwards. Commented Nov 12, 2020 at 11:49

2 Answers 2

2

The simplest way to do this (without the usage of any external package) is to write a simple class that reads the file. Then, call class multiple times.

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()
Sign up to request clarification or add additional context in comments.

Comments

0

although it is an unorthodox approach, one way of doing it is as such:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.