在matplotlib中为记号标签使用图像

2024-04-25 21:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列小的,固定宽度的图像,我想用它们来替换刻度标签。例如,考虑以下最小工作示例:

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

我想用自定义图像替换“0”。我可以turn off标签,load an image into an array并很好地显示它。但是,我不确定

  • 记号标签的位置,因为它们位于绘图之外。在
  • 使用imshow显示该图像,如果将其放入一个轴中,它将被“剪裁”。在

我的想法是用set_clip_on某种方式或自定义艺术家,但我没有取得太大进展。在


Tags: 图像importnumpyan示例size宽度as
1条回答
网友
1楼 · 发布于 2024-04-25 21:37:39

有趣的问题,并可能有许多可能的解决办法。这是我的方法,基本上首先计算标签'0'在哪里,然后使用绝对坐标在那里画一个新的轴,最后把图像放在那里:

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

相关问题 更多 >