简体   繁体   中英

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. In the connected function you can show an annotation, but also eg update the statusbar or write something in the console.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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