【问题标题】:Insert a png image in a matplotlib figure在 matplotlib 图中插入 png 图像
【发布时间】:2020-12-21 04:20:27
【问题描述】:

我正在尝试在 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-3.x image matplotlib plot png


    【解决方案1】:

    您可以缩放图像并将框对齐设置为右下角 (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 parameter doc

    【讨论】:

    • 嗨@Stef 当我尝试保存这个文件fig.savefig("output.svg", transparent=True, dpi=600, bbox_inches="tight")时,不幸的是我无法在输出图像中找到插图
    • savefig 对我有效(matplotlib 版本 3.3.1)。你用的是什么版本?
    • hm,我只能说它对我有用,没有任何问题,请参阅i.stack.imgur.com/OtUKI.png,完全使用您在评论或编辑中提供的命令。
    • 抱歉,上次忘记提版本了。我正在使用 matplotlib 3.3.3
    • here 是我的 output.svg 如上一条评论在浏览器中显示的那样,打开时它看起来正确吗?
    猜你喜欢
    • 2014-11-19
    • 2021-06-06
    • 2012-02-20
    • 2020-05-05
    • 2017-09-15
    • 2014-10-14
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多