在 matplotlib 图中插入 png 图像

问题描述 投票:0回答:1

我正在尝试在 matplotlib 图中插入 png 图像(ref

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox


ax = plt.subplot(111)
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )
arr_img = plt.imread("stinkbug.png")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()

插图:

获得的输出:

我想知道如何调整必须插入的图像的大小以避免重叠。

编辑: 保存图

ax.figure.savefig("output.svg", transparent=True, dpi=600, bbox_inches="tight")

python image matplotlib plot png
1个回答
7
投票

您可以缩放图像并将框对齐设置为右下角 (0,1) 以及一些额外的边距:

im = OffsetImage(arr_img, zoom=.45)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction', box_alignment=(1.1,-0.1))

您可能还想使用默认的数据坐标,并使用默认的 box_alignment 到中心,例如

ab = AnnotationBbox(im, (2.6, 1.45))
。有关各种坐标选项的更多信息,请参阅 xycoords 参数文档

© www.soinside.com 2019 - 2024. All rights reserved.