Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an image for tick labels in matplotlib [duplicate]

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.

like image 886
Hooked Avatar asked Jun 15 '14 04:06

Hooked


1 Answers

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

like image 124
CT Zhu Avatar answered Sep 18 '22 13:09

CT Zhu