2

I have a numpy array [(a1, x1), (a2, x2), ..., (a100, x100)] and I need to plot it such that a is my y-axis and x is my x-axis.

I know that it would be easier to have [a1, a2, ..., a100] and [x1, x2, ..., x100] as separate arrays to plot, but I'm doing a project, and I've been specifically told to do it this way, but am struggling.

Attempt 1 gave me a graph, but I think it's plotted a graph of a and x values against their numbers of order in the array.

Attempt 2, which was suggested by a matplotlib website just gave me a long error message.

# attempt 1 
plt.plot(array,'r.') 
plt.show()
plt.close()

# attempt 2 
plt.plot(array_1[0], array_1[1:],'r.') 
plt.show()
plt.close()

Any advice would be greatly appreciated. Thank you!

1
  • 1
    Just reshape and unpack to get the quantities you want: a, x = array.T followed by plt.plot(a,x), or unpack with the * operator: plt.plot(*array.T). In this sequence T is for transpose and loosely stated *(a,b,c,d) = a,b,c,d Commented Mar 31, 2019 at 18:50

1 Answer 1

1

Assuming your array is a numpy array with shape (100,2) you can do:

plt.plot(arr[:,1],arr[:,0])

The way to read this is:

[ first dimension, second dimension ] where : is "all of the dimension" and the indices 1 and 2 specify position in the dimension.

So the code arr[:,1] means "all the rows", "second element"

edit: After discussing with OP it appears that his/her array shape is actually (202,)

You can fix this by reshape.

array_1 = array_1.reshape(-1,2)
plt.plot(arr[:,1],arr[:,0])
Sign up to request clarification or add additional context in comments.

18 Comments

can you type arr.shape and report the result?
i just need the values of "type(arr)" and "arr.shape"
still not giving me the values for array_1.shape
all numpy arrays have a shape attribute so you can type print(array_1.shape) at the end of your code
print it out and report here.. otherwise i have to guess.
|

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.