MatplotLib按轴获取所有注释

Dav*_*zza 3 python matplotlib tkinter-canvas

我正在用Python和Tkinter做一个项目。我可以绘制数据数组,并且还实现了一个函数,当我用鼠标单击时可以在图上添加注释,但是现在我需要我添加的所有注释的列表。有什么办法吗?这是我添加注释的功能:

def onclick(self, event):

    clicked = []
    key = event.key
    x = event.xdata
    y = event.ydata

    x_d = min(range(len(self.x_data)), key=lambda i: abs(self.x_data[i] - x))
    local_coord = self.x_data[x_d - 6:x_d + 6]
    x_1 = max(local_coord)
    indx = np.where(self.x_data == x_1)[0][0]
    y_1 = self.y_data[indx]



    if key == "v":
        self.ax.annotate("{0}nm".format(int(x_1)), size=25,
                         bbox=dict(boxstyle="round",fc="0.8"),
                         xy=(x_1, y_1), xycoords='data',
                         xytext=(x_1, y_1+50), textcoords='data',
                         arrowprops=dict(arrowstyle="-|>",
                                         connectionstyle="bar,fraction=0",
                                         ))

    self.canvas.draw()
Run Code Online (Sandbox Code Playgroud)

Bar*_*art 7

您可以遍历所有ax子项,并检查该子项是否为类型matplotlib.text.Annotation

for child in ax.get_children():
    if isinstance(child, matplotlib.text.Annotation):
        print("bingo") # and do something
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要一个列表:

annotations = [child for child in ax.get_children() if isinstance(child, matplotlib.text.Annotation)]
Run Code Online (Sandbox Code Playgroud)