在matplotlib中使用ax.annotate返回箭头和文本

时间:2017-11-14 00:11:29

标签: python matplotlib

使用matplotlib的面向对象方法,是否有办法访问使用ax.annotate时绘制的箭头。

似乎此命令将文本作为对象返回,但不返回箭头。使用show_children命令时,我也找不到箭头。

请问这个箭头可以访问吗?我只想在我的情节上获得所有箭头并改变它们的颜色。

plt.plot(np.arange(5), 2* np.arange(5))
plt.plot(np.arange(5), 3*np.arange(5))
ax = plt.gca()

text = ax.annotate('TEST', xytext=(2,10), xy=(2,2), arrowprops=dict(arrowstyle="->"))

ax.get_children()

返回

[<matplotlib.lines.Line2D at 0x207dcdba978>,
 <matplotlib.lines.Line2D at 0x207de1e47f0>,
 Text(2,10,'TEST'),
 <matplotlib.spines.Spine at 0x207dcb81518>,
 <matplotlib.spines.Spine at 0x207de05b320>,
 <matplotlib.spines.Spine at 0x207de0b7828>,
 <matplotlib.spines.Spine at 0x207de1d9080>,
  <matplotlib.axis.XAxis at 0x207de1d9f28>,
 <matplotlib.axis.YAxis at 0x207de049358>,
 Text(0.5,1,''),
 Text(0,1,''),
 Text(1,1,''),
 <matplotlib.patches.Rectangle at 0x207de049d30>]

由于

1 个答案:

答案 0 :(得分:1)

首先请注意,可以使用color中的arrowprops参数在创建注释时设置箭头的颜色:

ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2), 
             arrowprops=dict(arrowstyle="->", color="blue"))

如果之后确实需要更改颜色,则需要从文本中获取箭头的补丁。
如果使用Annotation生成箭头,则Annotation对象具有属性arrow_patch。您可以使用它来访问箭头补丁,如

text = ax.annotate( ... )
text.arrow_patch.set_color("red")

当然,你可以循环遍历所有孩子并检查他们是否包含箭头。完整的例子:

import matplotlib.pyplot as plt
ax = plt.gca()

text = ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))
text2 = ax.annotate('TEST2', xytext=(.5,.5), xy=(.2,.2), arrowprops=dict(arrowstyle="->"))

# access each object individually
#text.arrow_patch.set_color("red")
# or

for child in ax.get_children():
    if isinstance(child,type(text)):
        if hasattr(child, "arrow_patch"):
            child.arrow_patch.set_color("red")

plt.show()