Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65874740/how-to-interact-with-bars-in-matplotlib-by-events

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

mplcursors could be an interesting approach. In the connected function you can show an annotation, but also e.g. 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...