Chenyang
Chenyang

Reputation: 11

How to plot a figure from a CSV file with different row

I want to plot a figure by using matplotlib, and when I read the CSV file, it alway exists a error: list index out of range, for example, my file is like this:

1,1,1,1,1,1
2,3,4,5,6,7
3,4,5,6
4,5,6,7
5,6
6,7

My program is this,

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)

Upvotes: 1

Views: 249

Answers (1)

stovfl
stovfl

Reputation: 15513

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

Count the Length of each Row Values and Step over in Pairs, for instance:

    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]

Tested with Python: 3.4.2

Upvotes: 1

Related Questions