Search code examples
pythonmatplotlibpositionpngpixel

Python pyplot define pixelwise position of imshow


I want to use the output of imshow + savefig from Python pyplot in a HTML canvas to plot on defined positions of the image (a spectrogram). For this I need to know the exact pixel position of the lower left and upper right of the imshow area inside the exported png file:

fig = plt.figure(figsize=(12,8))
...
plt.imshow(y,origin='lower',aspect='auto',cmap='YlOrRd')
...
fig.tight_layout()
...
fig.savefig('myimg.png') 

enter image description here

Is this even possible and if yes, how?


Solution

  • You can get the points by:

    locs = fig.transFigure.transform(plt.gca().get_position().get_points()).
    print(locs)
    

    (The origin will be the lower left corner of the figure.)