gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:17:55 27 4
gpt4 key购买 nike

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

6876.593750  1
6876.302246 1
6876.003418 0

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

提前致谢!

最佳答案

你只是读入了错误的数据。这是一种更简洁的方法:

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

关于python - 如何使用 matplotlib 从 .txt 文件中绘制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532298/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com