Skip to content

Instantly share code, notes, and snippets.

@mocquin
Created March 26, 2024 14:56
Show Gist options
  • Save mocquin/e07928efe3c488ad3388a1c6c72685cc to your computer and use it in GitHub Desktop.
Save mocquin/e07928efe3c488ad3388a1c6c72685cc to your computer and use it in GitHub Desktop.
Add context menu on right-click in matplotlib
%matplotlib qt
import matplotlib.pyplot as plt
from matplotlib.backends.qt_compat import QtCore, QtWidgets
import numpy as np
def on_button_release(event, ax):
if event.button != 3: # Right-click.
return
if event.inaxes is None:
return
if not event.inaxes is ax:
return
def the_callback():#, the_ax=the_ax):
event.inaxes.plot(np.random.randn(10))
print("who's there!?")
plt.draw()
# only handle Qt-like backends
gui_event = event.guiEvent
menu = QtWidgets.QMenu()
menu.addAction("Knock knock", the_callback)
point = (gui_event.globalPosition().toPoint()
if QtCore.qVersion().split(".")[0] == "6"
else gui_event.globalPos())
menu.exec(point)
fig, axes = plt.subplots(1,2)
axes[0].figure.canvas.mpl_connect("button_release_event", lambda event:on_button_release(event, ax=axes[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment