python - 将 png 插入/调整到绘图 [matplotlib]

标签 python image matplotlib plot imread

我正在使用 matplotlib 库在 python 中为我的论文绘制插图。在这个插图中,我有很多线、多边形、圆圈等。但是我还想从外部插入一个 .png 图像。

这是我目前正在尝试做的事情:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon

fig, ax = plt.subplots()

plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off')
ax.axis('off')

# drawing circle
ax.add_patch(
                plt.Circle((0, 0), 0.5, color = 'black')
            )
# drawing polygon
ax.add_patch(
        Polygon(
            [[0,0], [20, 15], [20, 40]],
            closed=True, fill=False, lw=1)
        )
# importing image
im = plt.imread("frame.png")
# defining image position/size
rect = 0.5, 0.4, 0.4, 0.4 # What should these values be?
newax = fig.add_axes(rect, anchor='NE', zorder=1)
newax.imshow(im)
newax.axis('off')

ax.set_aspect(1)
ax.set_xlim(0, 60)
ax.set_ylim(0, 40)
plt.show()

所以问题是,如何确定 rect = 0.5, 0.4, 0.4, 0.4 的值?例如,我希望我的 .png 的左下角位于点 [20, 15] 并且我希望它的高度为 25.

这是生成的图像:

nonadjusted image

但我希望将这个虚拟框架调整到我的多边形点,就像这样(这个是在 photoshop 中调整的):

adjusted in photoshop

P.S. 这是 linkframe.png 进行试验。

最佳答案

你能把你的线条和图片画在同一个轴上吗? 为此,请在 plt.imshow()

中使用 extent
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon


im='d:/frame.png'
img=plt.imread(im)
fig, ax = plt.subplots()

frame_height=25
x_start=20
y_start=15
ax.imshow(img,extent=[x_start,x_start+frame_height,y_start,y_start+frame_height])

ax.add_patch(
        Polygon(
            [[0,0], [20, 15], [20, 40]],
            closed=True, fill=False, lw=1)
        )
ax.set_xlim(0, 60)
ax.set_ylim(0, 40)
plt.show()

关于python - 将 png 插入/调整到绘图 [matplotlib],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837233/

相关文章:

python - 使用 Python 保存 AutoCAD 文件 (.dwg)

python - Django 中的多语言环境文件查找

python - .loc[] = value 在 Pandas 中返回 SettingWithCopyWarning

ios - 按钮的快速图像太大

python - x 轴为 24 小时的条形图,日期时间数据仅为本部分的开头

python - 检测 spacy 中的日期

php - 创建图像的缩放缩略图并以有组织的方式回显结果 3 列,无限行,每行每列一个图 block

css - CSS 是否加载带注释的图像?

python - 在 matplotlib 中绘制列表/数组的散点图

python - matplotlib 的主循环的阻塞是否可以限制为单个窗口/图形? - 即,Fig.show(blocking=True)