我想使用matplotlib绘制图形,当我读取CSV文件时,它总是存在错误:列表索引超出范围,例如,我的文件是这样的:
1,1,1,1,1,1
2,3,4,5,6,7
3,4,5,6
4,5,6,7
5,6
6,7
我的节目就是这个,
import csv
import matplotlib.pyplot as plt
with open('test.csv') as file:
csvreader = csv.reader(file, delimiter=',')
x1 = []
x2 = []
x3 = []
y1 = []
y2 = []
y3 = []
for row in csvreader:
x1.append(float(row[0]))
x2.append(float(row[2]))
x3.append(float(row[4]))
y1.append(float(row[1]))
y2.append(float(row[3]))
y3.append(float(row[5]))
line1 = plt.plot(x1, y1, '-', linewidth=1)
line2 = plt.plot(x2, y2, '-', linewidth=1)
line3 = plt.plot(x3, y3, '-', linewidth=1)
答案 0 :(得分:0)
问题:如何...来自...不同行的文件
计算每个行值的长度并逐步调整,例如:
csvreader = csv.reader(file, delimiter=',')
# Define a List[3] of Dict x, y, plot
lines = [{'x':[], 'y':[], 'plot':None} for l in range(3)]
for values in csvreader:
# Step over n CSV Values X,Y Pairs
for line, i in enumerate(range(0, len(values), 2)):
lines[line]['x'].append(float(values[i]))
lines[line]['y'].append(float(values[i+1]))
for line, xy in enumerate(lines,1):
print('line{}: x:{}, y:{}'.format(line, xy['x'], xy['y']))
for line, xy in enumerate(lines):
lines[line]['plot'] = plt.plot(lines[line]['x'], lines[line]['y'], '-', linewidth=1)
<强>输出强>:
line1: x:[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], y:[1.0, 3.0, 4.0, 5.0, 6.0, 7.0] line2: x:[1.0, 4.0, 5.0, 6.0], y:[1.0, 5.0, 6.0, 7.0] line3: x:[1.0, 6.0], y:[1.0, 7.0]
使用Python测试:3.4.2