9

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!

AlphaBetaGamma96
  • 567
  • 3
  • 6
  • 21
  • Upon first glance it looks like there are two spaces between your x data point and your y data point in the .txt file. You split it in your list comprehension along a single space, which would return you a list of the x point, a space, and a y point. – Peter Wang Jul 22 '16 at 17:36
  • data has four lines, not three – aless80 Jul 22 '16 at 17:40

4 Answers4

7

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']
Chris Arena
  • 1,602
  • 15
  • 17
6

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()
gunj_desai
  • 782
  • 6
  • 19
bxdm
  • 61
  • 1
  • 2
2

Chris Arena's answer is neat. Please keep in mind that you are saving str into a list. If you want to plot x and y using matplotlib, I suggest to change the format from 'str' to 'int' or 'float':

import matplotlib.pyplot as plt
with open('filename.txt', 'r') as f:
    lines = f.readlines()
    x = [float(line.split()[0]) for line in lines]
    y = [float(line.split()[1]) for line in lines]
plt.plot(x ,y)
plt.show()
anegru
  • 1,023
  • 2
  • 13
  • 29
1

A quick solution would be to remove the 4th element in data like this:

data.pop()

Place it after

data = data.split('\n')
aless80
  • 3,122
  • 3
  • 34
  • 53