sivasudhan sivasudhan - 1 year ago 77
Python Question

Plotting list of lists in a same graph in Python

I am trying to plot

where as
y = [[1,2,3],[4,5,6],[7,8,9]]

len(x) = len(y[1]) = len(y[2])
The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e,
(x, y[1],y[2],y[3],...)
. When I tried using loop it says
dimension error

I also tried:
plt.plot(x,y[i] for i in range(1,len(y)))

How do I plot ? Please help.

for i in range(1,len(y)):
plt.plot(x,y[i],label = 'id %s'%i)

Answer Source

Assuming some sample values for x, below is the code that could give you the desired output.

import matplotlib.pyplot as plt
x = [1,2,3]
y = [[1,2,3],[4,5,6],[7,8,9]]
plt.title("A test graph")
for i in range(len(y)):
    plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)

Assumptions: x and any element in y are of the same length. The idea is reading element by element so as to construct the list (x,y[0]'s), (x,y[1]'s) and (x,y[n]'s

Below is the plot I get for this case: Sample plot

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download