【问题标题】:plt.bar doesnt connect with click event (or any event) - python matplotlibplt.bar 不与点击事件(或任何事件)连接 - python matplotlib
【发布时间】:2019-11-27 14:51:44
【问题描述】:

我一直在网上寻找示例,它们似乎大致相同。当我尝试一个小例子时,它可以工作,但由于某种原因,我还没有让 plt.bar 工作。 (我正在使用 jupyter 笔记本)。

这是我显示图表的方式:

fig = plt.figure(figsize=(12, 10))

xpos = np.arange(len(df.T.mean()))
plt.bar(xpos, df.T.mean(), yerr=yerr, color=bar_colors, width=1, capsize=30, picker=True )

这是我的 on_click 函数:

def on_click(event):
    plt.cla()
    plt.gca().set_title("please just work")

这就是我的连接方式:

fig.canvas.mpl_connect('pick_event', on_click)

我还尝试了以下方法:

fig.canvas.mpl_connect('button_press_event', on_click)
fig.canvas.mpl_connect('motion_notify_event', on_click)
fig.canvas.mpl_connect('axes_enter_event', on_click)

#or the same with plt.gcf()
plt.gcf().canvas.mpl_connect('pick_event', on_click)

如何检测条形图上的点击事件?

编辑

我忘了澄清我只是想在这一点上连接点击事件。是的,我的点击事件现在应该只清除图表,但根本没有发生任何事情。

二次编辑

Server Information:
You are using Jupyter notebook.

The version of the notebook server is 4.2.3 and is running on:
Python 3.6.2 | packaged by conda-forge | (default, Jul 23 2017, 22:59:30) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]

Current Kernel Information:
Python 3.6.2 | packaged by conda-forge | (default, Jul 23 2017, 22:59:30) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

【问题讨论】:

  • 更改后忘记重绘画布。
  • 我对你的 on_click() 函数中的 plt.cla() 感到困惑。如果清除轴,则没有更多艺术家可供选择,因此您的功能将无法再触发
  • 我只是想从函数中看到任何东西。所以我期待一个空白图表。这只是我能想到的最直观的想法。
  • 对不起,我刚刚指定我现在想要完成的只是连接点击事件。我只是想看看发生了什么,然后我会做出必要的调整。
  • 您可能还没有选择任何交互式后端。

标签: python matplotlib plot jupyter-notebook bar-chart


【解决方案1】:

此代码在 jupyter notebook 上使用 notebook 后端运行良好。

如果这不适合您,您可能必须从 %matplotlib inline 切换到 %matplotlib notebook

def on_click(event):
    plt.gca().set_title("Click at {:.2f}/{:.2f}\non {:s}".format(event.mouseevent.x, event.mouseevent.y, event.artist.__repr__()))
    plt.gcf().canvas.draw_idle()  # doesn't seem to be absolutely required,
                                  # but doesn't hurt to put it in


fig, ax = plt.subplots()
ax.bar(np.arange(10), np.arange(10), picker=True)
fig.canvas.mpl_connect('pick_event', on_click)

【讨论】:

  • 我不会依赖画布重绘本身。见第一条评论。
  • 很公平,我的机器上不需要它,但也许这就是导致 OP 出现问题的原因
  • 您使用的是笔记本后端(%matplotlib notebook)还是内联后端(%matplotlin inline)?
  • 当然,我更新了我的答案。虽然你在你的问题中说你可以得到一些简单的例子,但只有条形图不起作用,这表明后端不是问题
  • 我明白了,现在说得通了。很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多