【问题标题】:How to interact with bars in matplotlib by events如何通过事件与 matplotlib 中的条进行交互
【发布时间】:2021-04-28 15:59:42
【问题描述】:
我正在尝试找到如何单击栏的解决方案。
例如,我的图表有五个条形图。
我单击第二个栏并尝试在控制台中打印:“您选择了第二个栏”。
如何通过点击或其他方式检测图中的元素?
【问题讨论】:
标签:
python-3.x
matplotlib
events
mplcursors
【解决方案1】:
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()