使用matplotlib从文本文件中读取三列
我的输入文件(text.txt)包括三列。第一列为x轴,第二列为y轴,第三列为y轴。当我运行代码时,我得到“x.append(float(line.split()[0]))索引器:列表索引超出范围”。我怎样才能纠正这个错误 我的代码:使用matplotlib从文本文件中读取三列,matplotlib,Matplotlib,我的输入文件(text.txt)包括三列。第一列为x轴,第二列为y轴,第三列为y轴。当我运行代码时,我得到“x.append(float(line.split()[0]))索引器:列表索引超出范围”。我怎样才能纠正这个错误 我的代码: #!/usr/bin/python import numpy as np import matplotlib.pyplot as plt with open("text.txt", "r") as data_file: lines=data_file.readl
#!/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)
my text.txt:input
# 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
但我不使用您发布的代码,而是使用以下方式解析文件:
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()
读取整个文件并返回字符串列表。这可能需要很多时间
如果文件较大,则返回内存。因此,除非确实需要将整个文件转换为字符串列表,否则不要使用lines=data\u file.readlines()
。否则,如果您可以使用
for line in f: