在matplotlib中使用图像作为刻度标签 [英] Using an image for tick labels in matplotlib

查看:60
本文介绍了在matplotlib中使用图像作为刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

我想用自定义图像替换0".我可以关闭标签,

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

  • 刻度标签的位置在哪里,因为它们位于图之外.
  • 使用 imshow 显示该图像,如果将其放入轴中将被剪裁".
  • 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.

我想以某种方式使用 set_clip_on 或自定义艺术家,但我没有取得太大进展.

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

推荐答案

有趣的问题,可能有许多可能的解决方案.这是我的方法,基本上首先计算标签'0'的位置,然后使用绝对坐标在那里绘制一个新轴,最后将图像放在那里:

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')

这篇关于在matplotlib中使用图像作为刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆