在matplotlib中使用图像作为刻度标签
•浏览 1
Using an image for tick labels in matplotlib
本问题已经有最佳答案,请猛点这里访问。
我有一系列固定宽度的小图像,我想用它们替换刻度标签。例如,考虑以下最小的工作示例:
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()
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')
我想用自定义图像替换"0"。我可以关闭标签,将图像加载到数组中并正常显示。但是,我不确定
- 刻度标签的位置在哪里,因为它们位于绘图之外。
- 使用 imshow 显示该图像,如果将其放入轴中,它将被"剪裁"。
我的想法是使用 set_clip_on 或自定义艺术家,但我没有取得太大进展。
有趣的问题,并且可能有许多可能的解决方案。这是我的方法,基本上是先计算标签'0'在哪里,然后用绝对坐标在那里画一个新轴,最后把图像放在那里:
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()
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')