11

I have a series of small, fixed width images and I want to replace the tick labels with them. For example, consider the following minimal working example:

import numpy as np
import pylab as plt

A = np.random.random(size=(5,5))
fig, ax = plt.subplots(1, 1)
ax.matshow(A)
plt.show()

enter image description here

I would like to replace the "0" with a custom image. I can turn off the labels, load an image into an array and display it just fine. However, I'm unsure of

  • Where the locations of the tick labels are, since they lie outside the plot.
  • Use imshow to display that image when it it will be "clipped" if put into an axis.

My thought were to use set_clip_on somehow or a custom artist, but I haven't made much progress.

Community
  • 1
  • 1
Hooked
  • 84,485
  • 43
  • 192
  • 261

1 Answers1

7

Interesting question, and potentially has many possible solutions. Here is my approach, basically first calculate where the label '0' is, then draw a new axis there using absolute coordinates, and finally put the image there:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pylab as pl

A = np.random.random(size=(5,5))
fig, ax = plt.subplots(1, 1)

xl, yl, xh, yh=np.array(ax.get_position()).ravel()
w=xh-xl
h=yh-yl
xp=xl+w*0.1 #if replace '0' label, can also be calculated systematically using xlim()
size=0.05

img=mpimg.imread('microblog.png')
ax.matshow(A)
ax1=fig.add_axes([xp-size*0.5, yh, size, size])
ax1.axison = False
imgplot = ax1.imshow(img,transform=ax.transAxes)

plt.savefig('temp.png')

enter image description here

CT Zhu
  • 52,648
  • 17
  • 120
  • 133