mpl-events: matplotlib event handling

mpl-events is a tiny library for simple and convenient matplotlib event handling with minimum boilerplate code. In other words, the library provides high-level API for using matplotlib event system.

Why do we need yet another library?

You need to handling matplotlib events if you want to manipulate figures and visualizations interactively. Matplotlib contains a low-level API for event handling: using FigureCanvasBase.mpl_connect and FigureCanvasBase.mpl_disconnect methods, string-based names of events and integer connection identifiers.

Here are a few things that might be helpful:

  • mpl-events provides high-level API, auto disconnecting and cleanup

  • Strings-based event types/names are not used. Intstead, mpl_events.MplEvent enum class is used for all event types.

  • Integer connection identifiers are not used. Instead, the connection between event and handler is incapsulated via class mpl_events.MplEventConnection

  • mpl-events objects do not own mpl figure and do not create additional references to figure or canvas

  • mpl-events provides convenient base class mpl_events.MplEventDispatcher that contains handlers API (with type-hints) for handling all mpl events inside one class without boilerplate code


Event dispatcher for handling all mouse events:

from matplotlib import pyplot as plt
from mpl_events import MplEventDispatcher, mpl

class MouseEventDispatcher(MplEventDispatcher):

    def on_mouse_button_press(self, event: mpl.MouseEvent):
        print(f'mouse button {event.button} pressed')

    def on_mouse_button_release(self, event: mpl.MouseEvent):
        print(f'mouse button {event.button} released')

    def on_mouse_move(self, event: mpl.MouseEvent):
        print(f'mouse moved')

    def on_mouse_wheel_scroll(self, event: mpl.MouseEvent):
        print(f'mouse wheel scroll {event.step}')

figure = plt.figure()

# setup figure and make plots is here ...

mouse_dispatcher = MouseEventDispatcher(figure)

Event connection to handle figure closing:

from matplotlib import pyplot as plt
from mpl_events import MplEvent, mpl

def close_handler(event: mpl.CloseEvent):
   print('figure closing')

figure = plt.figure()
conn = MplEvent.FIGURE_CLOSE.make_connection(figure, close_handler)


Indices and tables