How to Plot Data from Multiple Two Column Text Files With Legends in Matplotlib

How to plot multiple set of data from same text file in matplotlib

One idea can be to read the complete file, split it at the positions where a double line break occurs, .split('\n\n') and read in each part using numpy.loadtxt.

import numpy as np
from io import StringIO
import matplotlib.pyplot as plt

filename="data.txt"
with open(filename) as f:
data = f.read()

data = data.split('\n\n')

for d in data:
ds = np.loadtxt(StringIO(unicode(d)))
plt.plot(ds[:,0],ds[:,1])

plt.show()

How to plot legend into multiple column outside the plot canvas?

You can specify the position of the legend in relative coordinates using loc and use ncol parameter to split the single legend column into multiple columns. To do so, you need an axis handle returned by the df.plot

df = pd.read_csv('data.csv')
ax = df.plot(figsize = (10,7))
ax.legend(loc=(1.01, 0.01), ncol=4)
plt.tight_layout()

Sample Image

plot data from more than one text file using python

You can start the process by loading each file into a list.

with open("Xdata.txt", "r") as xf:
x_list = xf.readlines()

with open("Ydata.txt", "r") as yf:
y_list = yf.readlines()

Then, you make use of python's zip function to grab each pair of lines and plot them. This will pair line 1 in Xdata.txt with line 1 in Ydata.txt and so on:

for (x_line, y_line) in zip(x_list, y_list):
# Split out the data from the line, which is stored as a string
x_data = x_line.split(' ')
y_data = y_line.split(' ')

# Insert data conversion from string to numbers if needed

# Modify plotting code as needed
plot(x_data, y_data)

How to read a multiple column from a .dat file in matplotlib and then plot then into multiple subplots

In matplotlib subplots() is the first address for generating multiple plots into one figure.

(See link for description and examples.)

So you could do

fig, axs = pl.subplots(2)
axs[0].plot(x, y1)
axs[1].plot(x, y2)

instead of your plot command above.


However, please note that while reading a file like this is possible and correct, there are several tools which help you here so you do not have to program this very common task manually again and again.

The most important tools are imo numpy and pandas, perhaps you heard already about them and like to try yourself.

With numpy you could do

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt("sigma.dat")

fig, axs = plt.subplots(2)
for i, ax in enumerate(axs):
ax.plot(data[:, 0], data[:, i+1])

With pandas you could do

import pandas as pd

df = pd.read_csv("sigma.dat", delim_whitespace=True, index_col=0)
df.plot(subplots=True)

Short Explanation:

With numpy, you import an additional library along with matplotlib, which helps you not only with reading data from files, but which is in fact the basic needed library to do scientific math and calculations in python.

pandas on the other hand can replace matplotlib and/or numpy, as it is built on top of both. It is a complete data analysis tool with a wide range of functions included for a variaty of standard approaches in this topic.


Edit:

After reading your next question, I think I understand a little more of your task, so this is an approach in Python to create four subplots with no space in between:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sigma.dat', delim_whitespace=True, index_col=0, header=None)

fig, axs = plt.subplots(2, 2, sharex=True, sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0})

axs[0, 0].plot(df[df.columns[:2]])
axs[0, 1].plot(df[df.columns[:2]]*1.2)
axs[1, 0].plot(df[df.columns[2:]])
axs[1, 1].plot(df[df.columns[2:]]*.75)

Sample Image


EDIT2:

Further attempt to copy this handmade original

import matplotlib as mpl
mpl.rcParams['font.family'] = 'Times New Roman'

fig, axs = plt.subplots(2, 2, sharex=True, gridspec_kw={'hspace': 0, 'wspace': 0})

axs[0, 0].plot(df[df.columns[:2]])
axs[0, 1].plot(df[df.columns[:2]]*1.2)
axs[1, 0].plot(df[df.columns[2:]])
axs[1, 1].plot(df[df.columns[2:]]*.75)
for i in range(2):
axs[i, 1].spines['left'].set_position(('axes', 1))
axs[i, 1].yaxis.set_ticks_position('right')
axs[i, 1].yaxis.set_label_position('right')

axs[0, 0].set_ylabel('A11')
axs[0, 1].set_ylabel('A12')
axs[1, 0].set_ylabel('A21')
axs[1, 1].set_ylabel('A22')

for ax, lbl in zip(axs.flatten(), list('abcd')):
ax.text(.05, .9, f'({lbl})', transform=ax.transAxes)
axs[1, 0].set_xlabel('X-12-Scale', x=1)

Sample Image

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

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


Related Topics



Leave a reply



Submit