Skip to main content
 首页 » 编程设计

python之关于从 txt 文件数据绘图的问题

2024年12月31日9jiqing9006

从 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') 

请您参考如下方法:

我在文件 file.txt 中使用了你的三行数据,根据你的描述,这是我通过重写你的代码得到的情节。您不需要名为 index 的额外变量来标记您的 x-ticks。您可以直接绘制 x,x 刻度标签将自动设置。为了访问最后一列,我使用了索引 [-1]。这避免了对列进行计数并手动放置索引。我删除了图例,因为绘图命令中没有您定义的图例。

file = open("file.txt", 'r') 
data = file.readlines() 
data[0].split() 
x = [row.split()[-1] for row in data] # if no blank line in the file 
y = [row.split()[2] for row in data] # if no blank line in the file 
# x = [row.split()[-1] for row in data if row.strip()] # if blank lines in the file 
# y = [row.split()[2] for row in data if row.strip()] # if blank lines in the file 
 
index = range(len(x)) 
fig = plt.figure() 
ax1 = fig.add_subplot(111) 
ax1.plot(x ,y, '-ro') 

输出