简体   繁体   中英

Read data from multiple .txt files to plot on one graph in Python

The python code below works for plotting data (two columns separated by a space) from 3.txt files. However, I would like to plot data from more text files located in the same folder. Is there a way that I can read the data from all.txt files in the folder and plot them all on the same graph?

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('10mm.txt',sep='\s+',header=None)
data = pd.DataFrame(data)

x1 = data[0]
y1 = data[1]
plt.plot(x1, y1, label = "10 mm")

data = pd.read_csv('20mm.txt',sep='\s+',header=None)
data = pd.DataFrame(data)

x2 = data[0]
y2 = data[1]
plt.plot(x2, y2, label = "20 mm")

data = pd.read_csv('30mm.txt',sep='\s+',header=None)
data = pd.DataFrame(data)

x3 = data[0]
y3 = data[1]
plt.plot(x3, y3, label = "30 mm")

plt.xlim(0.15)
plt.ylim(0)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('')
plt.legend()
plt.show()

You can loop through the files in your directory and if it ends with .txt , you can load the data and plot it. Note that pd.read_csv() already returns a DataFrame so you don't need to convert data to a DataFrame again.

You have to replace directory with your directory path.

import os

# Replace this directory with your own directory. 
directory = 'C:/Users/admin'

for filename in os.listdir(directory):
    if filename.endswith(".txt") :
        data = pd.read_csv(filename, sep='\s+', header=None)
        # data = pd.DataFrame(data) # This step is redundant
        plt.plot(data[0], data[1], label = filename.split('.')[0])
    else:
        continue

plt.xlim(0.15)
# Rest of the code
plt.show()        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM