Skip to main content
 首页 » 编程设计

python之更改 matplotlib 中注释箭头的宽度

2025年04月02日15arxive

我正在使用 annotate 在 matplotlib 中绘制箭头。我想让箭头更粗。我想要的效果是带有细边线的双向箭头,我可以在其中控制箭头宽度,即不更改 linewidth。我在 this 之后尝试了 kwargs,例如 width answer 但这导致了错误,我也尝试了 arrowstyle 和 connectorstyle 的不同变体,但没有成功。我敢肯定这很简单!

到目前为止我的代码是:

import matplotlib.pyplot as plt 
 
plt.figure(figsize=(5, 5)) 
plt.annotate('', xy=(.2, .2),  xycoords='data', 
            xytext=(.8, .8), textcoords='data', 
            arrowprops=dict(arrowstyle='<|-|>', 
                            facecolor='w', 
                            edgecolor='k', lw=1)) 
plt.show() 

我正在使用 Python 2.7 和 Matplotlib 1.5.1

请您参考如下方法:

最简单的方法是使用 FancyBboxPatch使用 darrow(双箭头)选项。此方法的一个棘手部分是箭头不会围绕其尖端旋转,而是围绕定义箭头主体的矩形边缘旋转。我通过在旋转位置放置一个红点来证明这一点。

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
import matplotlib as mpl 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
 
#Variables of the arrow 
x0 = 20 
y0 = 20 
width = 20 
height = 2 
rotation = 45 
facecol = 'cyan' 
edgecol = 'black' 
linewidth=5 
 
# create arrow 
arr = patches.FancyBboxPatch((x0,y0),width,height,boxstyle='darrow', 
                             lw=linewidth,ec=edgecol,fc=facecol) 
 
#Rotate the arrow. Note that it does not rotate about the tip 
t2 = mpl.transforms.Affine2D().rotate_deg_around(x0,y0,rotation) + ax.transData 
 
 
plt.plot(x0,y0,'ro') # We rotate around this point 
arr.set_transform(t2) # Rotate the arrow 
 
 
ax.add_patch(arr) 
 
plt.xlim(10, 60) 
plt.ylim(10, 60) 
 
plt.grid(True) 
 
plt.show() 

给予: