【发布时间】:2018-09-25 22:34:27
【问题描述】:
从txt 文件中绘制数据时出现问题。我的txt 文件中有 7 列,我想使用最后一列和第三列(分别作为 x 轴和 y 轴)的数据,但该命令不起作用。
错误是:
x = [row.split()[6] for row in data]
> IndexError: list index out of range
我的代码是:
x = [row.split()[6] for row in data]
y = [row.split()[2] for row in data]
index = [i for i,val in enumerate(x)]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xticklabels(x)
ax1.plot(index ,y, c='r')
leg = ax1.legend()
plt.locator_params(nbins=len(index)-1)
plt.show()
这是我的txt 文件的一部分。
01.05.2016 00:01:00 313 U 42491,00069 -1,87 01.05.2016 00:02
01.05.2016 00:02:00 313 U 42491,00139 -1,87 01.05.2016 00:03
01.05.2016 00:03:00 313 U 42491,00208 -1,87 01.05.2016 00:04
如有必要,以下代码显示了我如何初始化数据:
import matplotlib.pyplot as plt
with open("tesy=t.txt") as f:
data = f.read()
data = data.split('\n')
【问题讨论】:
-
您的输入中是否有任何较短的/空白行?
-
尝试打印 row.split() 结果。你可以看到列。
-
一旦你拆分,你有 8 列,所以最后一列将是 [7] 索引
-
您确定正确加载数据吗?
-
请告诉我们你是如何初始化
datavariabe的?
标签: python matplotlib