matplotlib: how to put picture to a specific point of data-coordinate system

Viewed 945

I'm trying to add picture at the plot in specific place in it by a given coordinates in data-coordinate system. However it runs a little bit unpredicted. Here is a code snippet I wrote:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(5,5))

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.grid('on')

x = np.arange(0, 1, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
ax.plot(x, y)

im_orange = plt.imread('./test100x100_orange.png')
im_blue = plt.imread('./test100x100_blue.png')

x0, y0 = ax.transData.transform((0,0))
print('transData(0,0) = {}'.format(ax.transData.transform((0,0))))

ax.figure.figimage(im_orange, alpha=0.5)
ax.figure.figimage(im_blue, x0, y0, alpha=0.5)

ax.transData.transform((0,0)) returns transData(0,0) = [45. 45.] which is unexpected since doesn't represent actual position of (0,0) on the plot. Here is result image as well:

figimage strange behaviour

My base question is how to put picture left bottom corner exactly at (0,0) point in data-coordinates? And if possible please explain such behaviour of matplotlib.

Update. A few experiments on top. I've run a slightly modified script (provided below by Iammuratc but with plt.savefig() instead) in 3 modes:

  1. From python console (copy and paste): enter image description here
  2. Python script (something like python test.py: Result is the same as before. enter image description here
  3. ipython from Jupiter Notebook: Suboption A: plt.show() enter image description here

Suboption B: plt.savefig()

enter image description here

Now it's even more confusing..

1 Answers

It works for me how you did it. You might check the image arrays in case they are shifted.

import numpy as np
import matplotlib.pyplot as plt


im_orange  = np.zeros((128,128,3),'uint8')
im_orange[:,:,0] = 255

im_blue = np.zeros((128,128,3),'uint8')
im_blue[:,:,2] = 255


fig, ax = plt.subplots(figsize=(5,5))

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.grid('on')

x = np.arange(0, 1, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
ax.plot(x, y)

# im_orange = plt.imread('./test100x100_orange.png')
# im_blue = plt.imread('./test100x100_blue.png')

x0, y0 = ax.transData.transform((0,0))
print('transData(0,0) = {}'.format(ax.transData.transform((0,0))))

ax.figure.figimage(im_orange,x0,y0, alpha=0.5)
ax.figure.figimage(im_blue, x0, y0, alpha=0.5)

plt.show()

output

Related