Reputation: 79
I am trying to plot a range of data. My data consists of 49 variables and I want to split this into 7. I have my data stored in a text file consisting of two rows of x and y as following:
I want to split both rows by 7 and create an x,y plot so that it gives me seven lines on my graph. I tried doing this:
lines = f.readlines()
lines1 = lines1[0:6]
lines2 = lines2[7:14]
lines3 = lines3[15:21]
lines4 = lines4[21:28]
lines5 = lines5[28:35]
lines6 = lines6[35:42]
lines7 = lines7[43:49]
I would then put all of the above data in an array and the same process for the y values as well. Finally, I would plot the variables. But this is inefficient and requires alot of time. There must be an easier way, but I cannot think of it. Could someone help?
Upvotes: 1
Views: 193
Reputation: 39052
You can use NumPy's loadtxt
to read the data and then use a for loop to plot the x and the y coordinates in batches of 7. Below is a sample answer. Just replace sample.txt
by your actual file name (including the directory where the file is located).
import numpy as np
import matplotlib.pyplot as plt
x, y = np.loadtxt('sample.txt', unpack=True)
for i in range(0, 49, 7):
plt.plot(x[i:i+7], y[i:i+7])
plt.show()
EDIT Adding labels
for lab, i in enumerate(range(0, 49, 7)):
plt.plot(x[i:i+7], y[i:i+7], label='group %d' %lab)
plt.legend()
plt.show()
Upvotes: 1