19

I am trying to plot (x,y) where as y = [[1,2,3],[4,5,6],[7,8,9]].

Say, 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)
    plt.legend()
    plt.show()
6
  • 1
    You have an indentation error in the plot command. You are also starting the indexing from 1. {range (1,...) instead of range(0,...) ). I am assuming that is intentional. The code should work nonetheless. Kindly let us know the error you are facing Commented Oct 16, 2016 at 17:42
  • What are the x values? Any samples? Commented Oct 16, 2016 at 17:56
  • X=[1,2,3]. @Nikhil I am getting dimension error while plotting Commented Oct 16, 2016 at 18:03
  • I also tried ax=plt.subplot (111) and yet I get different plots for different Y's Commented Oct 16, 2016 at 18:05
  • Please check my solution below @sivasudhan Commented Oct 16, 2016 at 18:07

2 Answers 2

28

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.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(y[0])):
    plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
plt.legend()
plt.show()

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.

Edited: Adapt the code if y contains more lists.

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

Sign up to request clarification or add additional context in comments.

2 Comments

One improvement that would adapt y values with more than 3 lists (e.g y = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] ), is to set the range in the for loop as "for i in range(len(y[0])):"
When i execute your code i get: ‘list’ object has no attribute ‘tolist’
10

Use a for loop to generate the plots and use the .show() method after the for loop.

 import matplotlib.pyplot as plt
 for impacts in impactData:
     timefilteredForce = plt.plot(impacts)
     timefilteredForce = plt.xlabel('points')
     timefilteredForce = plt.ylabel('Force')

 plt.show()

impactData is a list of lists.

Here's the plot this code generated.

2 Comments

Thanks for this code! A minor point of correction, its pyplt.plot(impacts not pyplt.plt. cheers!
Thanks for catching that. I updated the import to match the standard plt call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.