2017-05-05 60 views
0

我想使用相同的注释来注释2个点,并且我希望有2个箭头指向1个注释。如何在matplotlib的注释中设置箭头的起点?

我有以下代码:

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() 

正如你可以在结果图中看到,它的作品(虽然它可能不是最优雅的方式,因为我有两个注解在完全相同的位置)。

Annotation

我,不过,不满的是:我想,让箭在完全相同的位置开始,目前他们似乎从注释的中心开始,我宁愿让他们从注释边缘的某个地方开始,以便它们的起点连接起来。

我该如何做到这一点?

回答

2

您可以注释箭头的起点。即让两个箭头从没有注释文本的相同位置开始,然后使用不带箭头的第三个注释来用文本注释此起始点。

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() 

enter image description here

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

+0

谢谢!对于*水平对齐*,垂直对齐*和“哈”是“va”吗? – Alf

+1

这是正确的。你实际上也可以使用'horizo​​ntalalignment =“left”',它只是很长的类型。 – ImportanceOfBeingErnest