Home > database >  How can I get multiple lines in plot?
How can I get multiple lines in plot?

Time:08-14

I made code like this.


import matplotlib.pyplot as plt
import pandas as pd

data1 = csv.reader(open('data.csv', encoding = 'cp949'))
next(data1)

year = []
preference = []

for i in range(8):
  preference.append([])

for i in range(2015, 2022):
  year.append(i)

for row in data1:
  for i in range(8):
    preference[i].append(float(row[i 3]))

plt.plot(year, preference)
plt.title('preference')
plt.xlabel('year')
plt.ylabel('percent(%)')

and I got error like this. x and y must have same first dimension, but have shapes (7,) and (8, 7)


year has 7 elements, and each list in preference has 7 elements. So I think there's same first dimension in x and y. Why this error happend?

CodePudding user response:

There are lots of tools that let you stay away from explicitly writing out loops in python:

year = list(range(2015, 2022))
preference = [row[3:11] for row in data1]

With numpy:

year = np.arange(2015, 2022)
preference = np.array([row[3:11] for row in data1])

Matplotlib requires that the number of rows in a 2D dataset match the number of elements in a 1D:

plt.plot(year, np.transpose(preference))
  • Related