简体   繁体   English

如何通过事件与 matplotlib 中的条进行交互

[英]How to interact with bars in matplotlib by events

I am trying to find solution how to click on bars.我正在尝试找到如何单击栏的解决方案。 For example, my chart has a five bars.例如,我的图表有五个条形图。 I click on the second bar and I try to print in the console: "You selected the second bar".我单击第二个栏并尝试在控制台中打印:“您选择了第二个栏”。 How can I detect elements in the figure by clicking or by any other way?如何通过单击或任何其他方式检测图中的元素?

mplcursors could be an interesting approach. mplcursors可能是一种有趣的方法。 In the connected function you can show an annotation, but also eg update the statusbar or write something in the console.在连接的 function 中,您可以显示注释,还可以更新状态栏或在控制台中写入内容。

import matplotlib.pyplot as plt
import mplcursors

prev = None

fig, ax = plt.subplots()
ax.bar(range(9), range(1, 10), align="center")
ax.set(xticks=range(9), xticklabels=[*'ABCDEFGHI'], title="Hover over a bar")

cursor = mplcursors.cursor(hover=True)

@cursor.connect("add")
def on_add(sel):
    global prev
    x, y, width, height = sel.artist[sel.target.index].get_bbox().bounds
    sel.annotation.set(text=f"{sel.target.index + 1}: {height}",
                       position=(0, 20), anncoords="offset points")
    sel.annotation.xy = (x + width / 2, y + height)
    bar_num = sel.target.index + 1
    postfix = "st" if bar_num == 1 else "nd" if bar_num == 2 else "rd" if bar_num == 3 else "th"
    if bar_num != prev:
        print(f"You hovered over the {bar_num}{postfix} bar.")
    prev = bar_num

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM