Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: coordinates convention of image imshow incompatible with plot

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

like image 375
Vinwim Avatar asked Mar 12 '23 01:03

Vinwim


1 Answers

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.

like image 56
tmdavison Avatar answered Mar 15 '23 05:03

tmdavison