pythonnumpymatplotlib

How to bind CTRL + scroll to a matplotlib figure?


I want to bind CTRL + scroll inside a matplotlib figure to a zoom function. I know that in matplotlib I can use fig.canvas.mpl_connect('key_press_event', buttonpressed) to bind a certain button to a function (buttonpressed) and use fig.canvas.mpl_connect('scroll_event', scrollused) to bind scrolling to a function (scrollused), but what is the best way to combine this two?

Is there a possibility to bind both combined to a single function call? Or do I have to resort to working around it? For example, setting a variable to true whenever CTRL is pressed and to false whenever it is released again, and checking for this variable in the scroll function call?

The binds can be found here.

Minimal working example of a figure with CTRL bind and scroll bind (but not combined):

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.rand(10))

def scrolled(event):
    print('scroll used')

def ctrlpressed(event):
    if event.key == 'control':
        print('CTRL pressed')

# Bind to figure
fig.canvas.mpl_connect('key_press_event', ctrlpressed)
fig.canvas.mpl_connect('scroll_event', scrolled)
fig.show()

Solution

  • You can check if event.key is ctrl inside the scrolled function:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    ax.plot(np.random.rand(10))
    
    def scrolled(event):
        if event.key == 'control':
            print('ctrl+scroll used')
    
    fig.canvas.mpl_connect('scroll_event', scrolled)
    fig.show()