0

我正在尝试找到如何单击栏的解决方案。例如,我的图表有五个条形图。我单击第二个栏并尝试在控制台中打印:“您选择了第二个栏”。如何通过单击或任何其他方式检测图中的元素?

4

1 回答 1

2

mplcursors可能是一种有趣的方法。在连接的功能中,您可以显示注释,也可以更新状态栏或在控制台中写入内容。

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()
于 2021-01-24T23:34:51.407 回答