0

I have multiple data set with names dat01, dat02,... so on! . I want to load these datasets using for loop or any other trick. Afterwards, I want to plot these datasets in a single plot. Right now I'm doing something like this

import numpy as np

data1=np.loadtxt("dat01.dat")
xData1, yData1 = np.hsplit(data1, 2)
x1 = xData1[:,0]
y1 = yData1[:,0]

data2=np.loadtxt("dat01.dat")
xData2, yData2 = np.hsplit(data2, 2)
x2 = xData2[:,0]
y2 = yData2[:,0]

# plotting these datasets
plt.plot(x1, y1)
plt.plot(x2,y2)

This method works but not a smart way. Are there other methods that can be employed to reduce the typing?

2 Answers2

0

Create a function that does it for some data object, and in a loop just load the data and call that function while incrementing the filename by one. Let's say you have 10 of those files:

def plot_data(data):
    xData, yData = np.hsplit(data, 2)
    x = xData[:,0]
    y = yData[:,0]
    plt.plot(x, y)

for i in range(10):
    data = np.loadtxt(f"dat0{i}.dat")
    plot_data(data)

plt.show()

If your file names start from "dat01.dat", then just replace the range to range(1, 10). And if you have a problem with a leading zero in numbers<10, then use np.loadtxt("dat%02d.dat" % i).

leed
  • 312
  • 2
  • 6
  • Thanks! I have datasets from dat0001,...dat0020. What changes I can do to take into account all data sets? –  May 15 '21 at 09:13
  • Then the range should be `range(1, 21)` and the data loading should be `np.loadtxt("dat00%02d.dat" % i)`. Just remove the file extension if it's not necessary (.dat). – leed May 15 '21 at 09:20
  • One last thing! Is it possible to add a legend in loop. I want to see which plot represents which data set? –  May 15 '21 at 09:27
  • @user2338823 added a call to `plt.legned()` below which should work. As for `plt.title()`, it is not effective since we only have one axis which contains multiple line plots, so there is need for only one title independent of `i`. – leed May 15 '21 at 14:47
0
def plot_data(data,i):
    xData, yData = np.hsplit(data, 2)
    x = xData[:,0]
    y = yData[:,0]
    plt.plot(x, y)
    plt.legend("Graph number {index}".format(index=i))
# I do think a Graph title in more appropriate than a legend in this case.
# since you asked for a legend, please find it above.
# Here is how I would do a title.
    plt.title("Graph number {index}".format(index=i))

for i in range(10):
    data = np.loadtxt(f"dat0{i}.dat")
    plot_data(data,i)

plt.show()
user2338823
  • 501
  • 1
  • 3
  • 16