Skip to main content
 首页 » 编程设计

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

2025年04月02日13haluo1

我正在使用 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.

这是生成的图像:

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

P.S. 这是 link到 frame.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()