8

I have a problem of plotting points over a image using matplotlib.pyplot.

As we know, the convention of imshow is that the origin is located on the top left corner, x-axis pointing downward and y-axis pointing rightward.

But when I use plt.plot() to plot some points, the axes seem to becomes x-axis pointing rightward and y-axis pointing downward.

Here is an example. The location of the cursor shown in the windows is x=434 and y=162. However, from the convention of imshow, it should be x=162 and y=434.

Is there a way to ask plot function to obey the convention of imshow, or just let imshow to put the origin at lower left to follow the convention of plot. Thank you very much!

cursor location

1
  • 3
    Remember that array indexing is (row, column) -> (y, x) but by math conventions / plotting we specify points (x, y). Commented Jun 8, 2016 at 17:37

1 Answer 1

9

plt.imshow has an option called origin, which changes where the origin is placed. From the docs:

origin : [‘upper’ | ‘lower’], optional, default: None

Place the [0,0] index of the array in the upper left or lower left corner of the axes. If None, default to rc image.origin.

It would seem form your description, you want to set origin = 'lower'

To switch the x and y axes around, you will also need to transpose your image array. Consider this example:

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook

image_file = cbook.get_sample_data('ada.png')
img = plt.imread(image_file)

fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2)

ax1.imshow(img, origin='upper')
ax2.imshow(img, origin='lower')
ax3.imshow(img.transpose(1,0,2), origin='upper')
ax4.imshow(img.transpose(1,0,2), origin='lower')

ax3.set_xlabel('upper')
ax4.set_xlabel('lower')

ax1.set_ylabel('Not transposed')
ax3.set_ylabel('Transposed')

plt.show()

enter image description here

I think you want the lower right axes, so ax4.imshow(img.transpose(1,0,2), origin='lower'). Note that to transpose the image array, we must keep the RGBA channel as the last axes, hence the (1,0,2), to transpose just the first and second axes.

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

3 Comments

Thanks for your answer. After trying this option, what it did is just flip the y-axis, so it's pointing upward now. But the x-axis is still horizontal, not pointing downward.
So, I think you want to transpose your data array then?
Yes, the last one is what I want. Thank you!

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.