I want to plot a txt file using matplotlib but I keep getting this error message. I'm not that familiar with python, as I started learning a couple of weeks ago. The text file is formatted like (it is 2048 rows long):
6876.593750 1
6876.302246 1
6876.003418 0
I would like to plot the data from the txt. file.
The error message is [IndexError: list index out of range]
The code I'm using is:
import numpy as np
import matplotlib.pyplot as plt
with open("Alpha_Particle.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title")
ax1.set_xlabel('x label')
ax1.set_ylabel('y label')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
Thank you in advance!
You're just reading in the data wrong. Here's a cleaner way:
with open('Alpha_Particle.txt') as f:
lines = f.readlines()
x = [line.split()[0] for line in lines]
y = [line.split()[1] for line in lines]
x
['6876.593750', '6876.302246', '6876.003418']
y
['1', '1', '0']
maybe you can use pandas or numpy
import pandas as pd
data = pd.read_csv('data.txt',sep='\s+',header=None)
data = pd.DataFrame(data)
import matplotlib.pyplot as plt
x = data[0]
y = data[1]
plt.plot(x, y,'r--')
plt.show()
this is my data
1 93
30 96
60 84
90 84
120 48
150 38
180 51
210 57
240 40
270 45
300 50
330 75
360 80
390 60
420 72
450 67
480 71
510 7
540 74
570 63
600 69
The output looked like this
With Numpy, you can also try it with the following method
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.txt')
x = data[:, 0]
y = data[:, 1]
plt.plot(x, y,'r--')
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With