使用 matplotlib 从文本文件中读取三列

read three columns from a text file using matplotlib

我的输入文件 (text.txt) 包括三列。第一列属于 x 轴,第二列代表 y 轴,第三列再次代表 y 轴。当我 运行 我的代码时,我得到 "x.append(float(line.split()[0])) IndexError: list index out of range"。我该如何修复该错误?

我的代码:

#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt

with open("text.txt", "r") as data_file:
lines=data_file.readlines()
x=[]
y1=[]
y2=[]
counter=0
 for line in lines:
 if((line[0]!='#') and (line[0]!='@')):
 x.append(float(line.split()[0]))
 y1.append(float(line.split()[0]))
 y2.append(float(line.split()[1]))
 counter+=1
plt.plot(x, y1, y2)
plt.savefig("text.png", dpi=300)

我的text.txt:输入

# Carbon
# Gallium 
#
@ title 
@ xaxis  
1.00    2.12    14.51   
2.00    4.54    18.14
3.00    6.12    45.11
4.00    9.02    89.15
5.00    6.48    49.99
6.00    8.01    92.33
7.00    7.56    95.14
8.00    5.89    96.01

您遇到错误

IndexError: list index out of range

因为您的数据文件包含空行。它们可能位于文件末尾。

您可以通过包含

来修复它
for line in lines:
    if not line.strip(): continue

但我会使用 NumPy's genfromtxt 以这种方式解析文件,而不是您发布的代码:

import numpy as np
import matplotlib.pyplot as plt

with open("text.txt", "r") as f:
    lines = (line for line in f if not any(line.startswith(c) for c in '@#'))
    x, y1, y2 = np.genfromtxt(lines, dtype=None, unpack=True)

plt.plot(x, y1, x, y2)
plt.savefig("text2.png", dpi=300)

如果您想以最少的更改修复原始代码,它可能看起来像这样:

with open("text.txt", "r") as f:
    x = []
    y1 = []
    y2 = []
    for line in f:
        if not line.strip() or line.startswith('@') or line.startswith('#'): 
            continue
        row = line.split()
        x.append(float(row[0]))
        y1.append(float(row[1]))
        y2.append(float(row[2]))

    plt.plot(x, y1, x, y2)
    plt.savefig("text.png", dpi=300)

提示:readlines() 读取整个文件和 returns 一个字符串列表。这可能需要很多 如果文件很大,内存。因此,除非您确实需要将整个文件转换为字符串列表,否则永远不要使用 lines=data_file.readlines()。否则,如果您可以使用

一次处理每一行,则需要更少的内存
for line in f: