如何使用 matplotlib 从 .txt 文件中绘制数据? [英] How can you plot data from a .txt file using matplotlib?
本文介绍了如何使用 matplotlib 从 .txt 文件中绘制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用matplotlib绘制txt文件,但我一直收到此错误消息.我对Python不太熟悉,因为我几周前才开始学习.文本文件的格式如下(2048 行):
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
我想从txt中绘制数据.文件.
错误信息是[IndexError: list index out of range]
I would like to plot the data from the txt. file.
The error message is [IndexError: list index out of range]
我正在使用的代码是:
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()
先谢谢你!
推荐答案
你只是读错了数据.这是一种更清洁的方法:
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']
这篇关于如何使用 matplotlib 从 .txt 文件中绘制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文