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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38532298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:05:42  来源:igfitidea点击:

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

pythonmatplotlib

提问by AlphaBetaGamma96

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

我想使用 matplotlib 绘制一个 txt 文件,但我不断收到此错误消息。我对 python 不太熟悉,因为我几周前开始学习。文本文件的格式如下(2048 行长):

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]

我想绘制txt中的数据。文件。
错误信息是 [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!

先感谢您!

回答by Chris Arena

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']

回答by aless80

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

一个快速的解决方案是删除数据中的第四个元素,如下所示:

data.pop()

Place it after

放在后面

data = data.split('\n')

回答by Hoss

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':

Chris Arena的回答很简洁。请记住,您正在将 str 保存到列表中。如果您想使用 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()

回答by bxdm

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