3

I would like to plot a single row from a 2-dimensional numpy array against a 1d list in python. For example, I would like to plot using matplotlib row 'i' as below

  |0 0 0 0 0|
  |1 1 1 1 1|
i |2 2 2 2 2|
  |. . . . .|
  |n n n n n|

against

[0, 100, 200, 300, 400]

What I have currently is:

plt.plot(list1, 2dimArray[i])

but this is not working. I had this functionality working when I was plotting 1d lists against 1d lists but I had to go multidimensional and chose numpy.

Is there anyway to do this?

1
  • 1
    If A is your 2D array, and x your 1D list, does plt.plot(x, A[i,:]) works? Commented Apr 8, 2013 at 3:09

1 Answer 1

2

Using the data from your comment below, this works for me:

In [1]: import numpy as np

In [2]: x = np.arange(0,1100,100)

In [3]: y = np.random.rand(6,11)

In [4]: i = 2

In [5]: plt.plot(x, y[i])
Out[5]: [<matplotlib.lines.Line2D at 0x1043cc790>]

plot of row 2

The the thing is that the x and y arguments to plot must have the same shape (or at least the same first entry to shape).

In [6]: x.shape
Out[6]: (11,)

In [7]: y.shape
Out[7]: (6, 11)

In [8]: y[i].shape
Out[8]: (11,)

Perhaps one of your items generated by your program doesn't actually have the shape you believe it does?

This should also work if you use a list together with a numpy array (plt.plot will probably convert the list to an array):

In [9]: xl = range(0, 1100, 100)

In [10]: plt.plot(xl, y[i])
Out[10]: [<matplotlib.lines.Line2D at 0x10462aed0>]
Sign up to request clarification or add additional context in comments.

6 Comments

This is the error I am getting: ValueError: x and y must have same first dimension
Can you tell us what b.shape and a.share are?
x: 1d list constructed as such [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] y: 2dim array constructed as such np.zeros( (6,11) )
@user1535701 I can still get it to work using the data you supply. See my edit. Are you sure the shapes match?
could it have to do with the fact that my y variable is an array and my x variable is a list? or do the two play nicely with one another with respect to plotting?
|

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.