简体   繁体   English

如何使用 matplotlib 从 .txt 文件中绘制数据?

[英]How can you plot data from a .txt file using matplotlib?

I want to plot a txt file using matplotlib but I keep getting this error message.我想使用 matplotlib 绘制一个 txt 文件,但我不断收到此错误消息。 I'm not that familiar with python, as I started learning a couple of weeks ago.我对 python 不太熟悉,因为我几周前开始学习。 The text file is formatted like (it is 2048 rows long):文本文件的格式如下(2048 行长):

6876.593750  1
6876.302246  1
6876.003418  0

I would like to plot the data from the txt.我想绘制txt中的数据。 file.文件。
The error message is [IndexError: list index out of range]错误信息是 [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也许你可以使用 pandas 或 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用Numpy也可以用下面的方法试试

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()

A quick solution would be to remove the 4th element in data like this:一个快速的解决方案是删除数据中的第四个元素,如下所示:

data.pop()

Place it after放在后面

data = data.split('\n')

Chris Arena 's answer is neat. Chris Arena的回答很简洁。 Please keep in mind that you are saving str into a list.请记住,您正在将 str 保存到列表中。 If you want to plot x and y using matplotlib, I suggest to change the format from 'str' to 'int' or 'float':如果您想使用 matplotlib 绘制 x 和 y,我建议将格式从 'str' 更改为 'int' 或 '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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM