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

Python 在matplotlib中使用ax.annotate返回箭头和文本,python,matplotlib,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

使用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>]
[,,
,
文本(2,10,“测试”),
,
,
,
,
,
,
文本(0.5,1,,),
文本(0,1,,),
文本(1,1,,),
]

谢谢

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

ax.annotate('TEST', xytext=(.2,.1), xy=(.2,.2), 
             arrowprops=dict(arrowstyle="->", color="blue"))
如果以后确实需要更改颜色,则需要从文本中获取箭头的补丁。
如果使用
注释生成箭头
,则
注释
对象具有一个属性
arrow\u 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()