在matplotlib中将小图像放在图形角落

3 投票
2 回答
7312 浏览
提问于 2025-04-18 17:10

这个问题引用了Joe Kington的代码,内容是关于如何在使用matplotlib绘图时,在图的角落插入一张小图片。

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('/home/jofer/logo.png')
height = im.size[1]

# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255

fig = plt.figure()

plt.plot(np.arange(10), 4 * np.arange(10))

# With newer (1.0) versions of matplotlib, you can 
# use the "zorder" kwarg to make the image overlay
# the plot, rather than hide behind it... (e.g. zorder=10)
fig.figimage(im, 0, fig.bbox.ymax - height)

# (Saving with the same dpi as the screen default to
#  avoid displacing the logo image)
fig.savefig('/home/jofer/temp.png', dpi=80)

plt.show()

我尝试了以下代码:

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('/home/po/pic.jpg')
height = im.size[1]

im = np.array(im).astype(np.float) / 255

fig = plt.figure()
fig.subplots_adjust(top=0.80)
fig.patch.set_facecolor('black')
ax1 = fig.add_subplot(1, 1, 1, axisbg='white')

fig.figimage(im, 0, fig.bbox.ymax - height)

但是我的图片显示在中心,而不是我想要的位置。有没有办法把它往上移动一点?我试着去了解http://effbot.org/imagingbook/image.htm,但没有找到解决办法。

提前谢谢大家!:)

2 个回答

1

根据你的具体需求,有时候在照片编辑软件里直接调整图片大小会更快、更简单。然后你只需要写两行代码就可以了:

    img = image.imread("my_image.png")
    plt.figimage(img, 100, 200, zorder=1, alpha=0.3)
8

我觉得没有必要再额外导入一个模块,因为matplotlib本身就能做到同样的事情。

如果你想要做一个插图,只需要在图形窗口中添加一个额外的坐标轴对象并进行定位。这样做比使用figimage方法有一些好处,因为figimage

会将一个未经过重采样的图像添加到图形中

(来自matplotlib文档)。

这里有一个例子:

from scipy import misc
face = misc.face()
import matplotlib.pyplot as plt

plt.plot(range(10), range(10))
ax = plt.axes([0.5,0.8, 0.1, 0.1], frameon=True)  # Change the numbers in this array to position your image [left, bottom, width, height])
ax.imshow(face)
ax.axis('off')  # get rid of the ticks and ticklabels
plt.show()

我用face作为图像,这样任何人都可以运行这个代码,但你也可以通过输入以下命令让matplotlib加载你的图像:

image = plt.imread('/home/po/pic.jpg')

这样就替代了你对Image模块的调用,使其变得不再必要。变量image的作用和上面小脚本中的变量face是一样的。

撰写回答