这个问题借用了 Joe Kington ( how to insert a small image on the corner of a plot with 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但无济于事
提前致谢:)
最佳答案
当 matplotlib 有能力执行相同操作时,我认为不需要额外的模块导入。
如果您想制作插图,只需将一个额外的轴对象添加(并定位)到图形窗口即可。它比这里的 figimage
方法有一些优势,因为 figimage
Adds a non-resampled image to the figure
(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
与上面小脚本中的变量 face
的作用相同。
关于python - 使用 matplotlib 将小图像放在绘图的一角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25291322/