Skip to main content
 首页 » 编程设计

python之如何在 matplotlib 的注释中设置箭头的起点

2025年05月04日24lhb25

我想用相同的注释来注释 2 个点,并且我希望有 2 个箭头从那个 1 个注释指向这些点。

我有以下代码:

import matplotlib.pyplot as plt 
 
plt.plot( [1,2], [1,2], 'o' ) 
plt.xlim( [0,3] ) 
plt.ylim( [0,3] ) 
 
plt.annotate( 'Yet another annotation', xy=(1,1), 
              xytext=(1.5, .5), 
              arrowprops=dict( arrowstyle="->" ) 
            ) 
plt.annotate( 'Yet another annotation', xy=(2,2), 
              xytext=(1.5, .5), 
              arrowprops=dict( arrowstyle="->" ) 
            ) 
 
plt.show() 

正如您在结果图中看到的那样,它有效(尽管它可能不是最优雅的方式,因为我在完全相同的位置有两个注释)。

然而,我对此并不满意:我想让箭头从完全相同的位置开始,目前它们似乎从注释的中心开始,我更愿意让它们从边缘的某个地方开始注释,以便它们的起点连接。

我该如何实现?

请您参考如下方法:

您可以注释箭头的起点。 IE。让两个箭头在没有注释文本的相同位置开始,并使用第三个没有箭头的注释用文本注释这个起点。

import matplotlib.pyplot as plt 
 
plt.plot( [1,2], [1,2], 'o' ) 
plt.xlim( [0,3] ) 
plt.ylim( [0,3] ) 
 
plt.annotate( "", xy=(1,1), xytext=(1.3, 2.5), 
              arrowprops=dict( arrowstyle="->" ) ) 
plt.annotate( '', xy=(2,2), xytext=(1.3, 2.5), 
              arrowprops=dict( arrowstyle="->" ) ) 
plt.annotate( 'Some annotation', xy=(1.3, 2.5), 
              xytext=(1.3, 2.5) , va = "bottom", ha="center" ) 
 
plt.annotate( "", xy=(1,1), xytext=(1.5, .5), 
              arrowprops=dict( arrowstyle="->",shrinkA=0 ) ) 
plt.annotate( '', xy=(2,2), xytext=(1.5, .5), 
              arrowprops=dict( arrowstyle="->",shrinkA=0 ) ) 
plt.annotate( 'Yet another annotation', xy=(1.5, .5), 
              xytext=(1.5, .5) , va = "top", ha="left" ) 
 
plt.show() 

您可以使用 arrowprops 键 shr​​inkA 来调整箭头的收缩,将其设置为零让两个箭头连接起来。