如何用不同的

2024-04-18 19:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

Tags: 文件csvplotmatplotlibpltfloatrowx1
1条回答
网友
1楼 · 发布于 2024-04-18 19:31:32

Question: How to ... from ... file with different row

计算每行值的长度并成对跨接,例如:

    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)

Output:

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测试

相关问题 更多 >