Skip to main content
 首页 » 编程设计

python之为一个 matplotlib 图读取两个数据集

2024年10月24日8unruledboy

我尝试在一个图中绘制两个数据集,包括误差线。它对一个数据集工作得很好。但是在这个“解决方案”中:

from __future__ import print_function 
from matplotlib import pyplot as plt 
import numpy as np 
 
f2 = open('data1.txt', 'r') 
lines = f2.readlines() 
f2.close() 
 
f3 = open('data2.txt', 'r') 
lines2 = f3.readlines() 
f3.close() 
 
x1 = [] 
y1 = [] 
xerr1 = [] 
yerr1 = [] 
 
x2 = [] 
y2 = [] 
xerr2 = [] 
yerr2 = [] 
 
 
for line in lines: 
    p = line.split() 
    x1.append(float(p[0])) 
    y1.append(float(p[1])) 
    xerr1.append(float(p[2])) 
    yerr1.append(float(p[3])) 
 
for line2 in lines2: 
    k = line2.split() 
    x2.append(float(k[0])) 
    y2.append(float(k[1])) 
    xerr2.append(float(k[2])) 
    yerr2.append(float(k[3])) 
 
 
xv = np.array(x1) 
yv = np.array(y1) 
xerror = np.array(xerr1) 
yerror = np.array(yerr1) 
 
xv2 = np.array(x2) 
yv2 = np.array(y2) 
xerror2 = np.array(xerr2) 
yerror2 = np.array(yerr2) 
 
fig = plt.figure() 
 
 
ax1 = fig.add_subplot(111) 
 
ax1.set_title("test", fontweight='bold')     
ax1.set_xlabel('test', fontsize=14, fontweight='bold') 
ax1.set_ylabel('test', fontsize=16, fontweight='bold') 
ax1.grid(True) 
plt.ylim(67.2, 70.75)  
plt.xlim(-45, 30)  
 
 
plt.errorbar(xv, yv, xerr=xerror, yerr=yerror, fmt='-o', linestyle='None', color='k', marker='.') 
plt.errorbar(xv2, yv2, xerr=xerror2, yerr=yerror2, fmt='-o', linestyle='None', color='k', marker='.') 
 
plt.plot(xv, yv, marker='o', markersize='6', markeredgewidth='0', linestyle='None', linewidth=0, color='b') 
plt.plot(xv2, yv2, marker='o', markersize='6', markeredgewidth='0', linestyle='None', linewidth=0, color='r') 
 
plt.show() 

我只得到错误

exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) 
File "E:/script.py", line 39, in <module> 
        x2.append(float(k[0])) 
    IndexError: list index out of range 

我没有看到错误,需要一些帮助。有人知道这种方式有什么问题吗?我希望这不会太容易...

请您参考如下方法:

您可能在 for line2 in lines2: 中有一个空行,因为它给出了 IndexError: list index out of range for k[0],意味着索引 0 在这种情况下对于 k 不存在。 请务必检查拆分结果是否为空。

例如:

for line2 in lines2: 
    k = line2.split() 
    if len(k)==0: 
       #do something 
    else: 
       x2.append(float(k[0])) 
       y2.append(float(k[1])) 
       xerr2.append(float(k[2])) 
       yerr2.append(float(k[3])) 

第一个 for 循环也应该这样做。