Alessandro Peca
Alessandro Peca

Reputation: 923

import and plot data from multiple files without too many lines

I wrote a code that imports columns from a text file and plots them like this:

import os
import numpy as np
import matplotlib.pyplot as plt

dataset = np.genfromtxt(fname='filename.dat')
x=dataset[:,3]  # column select
y=dataset[:,2] 

plt.semilogx()
#plt.semilogy()
plt.xlabel('x')
plt.ylabel('y')
plt.title ('title')

plt.plot(x, y, color='red', linewidth=1)  
plt.show() 

The problem is that I would plot many more filename.dat (always columns 3 and 2 in every filename.dat). At the moment I have 23 filename.dat that I would like to plot all together in the same plot. These filename.dat are named as:

filename01.dat
filename02.dat
...
filename23.dat

I know I could rewrite the lines:

dataset_ = np.genfromtxt(fname='filename_.dat')
x_=dataset_[:,3] 
y_=dataset_[:,2]
# where '_' is the number of each filename.dat
plt.plot(x_, y_, color='red', linewidth=1) 

For each filename.dat, but is there a faster and more practical way (with np.genfromtxt and put.plot) to not rewrite the same lines for 23 times?

UPDATE: I would also like a different color for each file.

Upvotes: 0

Views: 1233

Answers (1)

DavidG
DavidG

Reputation: 25362

You can use a for loop. Make sure to initialise your figure before the loop if you want to plot all 23 lines on the same axis:

import os
import matplotlib.pyplot as plt
import numpy as np

filenames = os.listdir(your_path) # get a list of filenames

fig, ax = plt.subplots()    # create a figure

for file in filenames:
    dataset = np.genfromtxt(file)

    x=dataset[:,3]  # column select
    y=dataset[:,2]

    ax.plot(x, y)

ax.set_xscale("log")
ax.set_xlabel("x")
ax.set_ylabel("y")

plt.show()

If you remove color = in your ax.plot() then matplotlib should automatically change the color of each line for you. However, as @jack6e suggested in the comments, in order to plot your own colours, you can create a list (c_list) with the colours in it and then do:

for i, file in enumerate(filenames):   
    # your code

    ax.plot(x, y, color=c_list[i])

Upvotes: 2

Related Questions