【问题标题】:How to interact with bars in matplotlib by events如何通过事件与 matplotlib 中的条进行交互
【发布时间】:2021-04-28 15:59:42
【问题描述】:

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

【问题讨论】:

  • 希望答案是有帮助的。彻底回答问题很费时间。如果您的问题已解决,请接受解决方案 位于答案左上角的 ▲/▼ 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您还可以使用 ▲/▼ 箭头对答案的有用性进行投票。 如果解决方案无法回答问题,请发表评论。 What should I do when someone answers my question?。谢谢。

标签: 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()

【讨论】:

  • JohanC,非常感谢您的解决方案!它工作正常。
  • 如果这解决了您的问题,请随时mark 接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2010-09-17
  • 2018-01-21
  • 2018-04-08
相关资源
最近更新 更多