Trying to use keyboard shortcuts for interactive plot navigation

I’d like to be able to zoom in on my figures without using the toolbar. I see keyboard shortcuts listed here: Interactive navigation — Matplotlib 3.2.2 documentation

I tried them on a very simple example plot (I’m using Spyder IDE):

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel=‘time (s)’, ylabel=‘voltage (mV)’,
title=‘About as simple as it gets, folks’)


But when I try the keyboard shortcuts on the figure, nothing happens. For example, holding down the letter “p” (for panning) while clicking and dragging my mouse pointer on the plot.

Those shortcuts are for the toolbar; if you disable the toolbar then they won’t be registered.

I found this example with a toolbar, and I still can’t get the keyboard shortcuts to work for me.

# importing various libraries
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
# main window
# which inherits QDialog
class Window(QDialog):
    # constructor
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        # a figure instance to plot on
        self.figure = plt.figure()
        # this is the Canvas Widget that 
        # displays the 'figure'it takes the
        # 'figure' instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)
        # Just some button connected to 'plot' method
        self.button = QPushButton('Plot')
        # adding action to the button
        # creating a Vertical Box layout
        layout = QVBoxLayout()
        # adding tool bar to the layout
        # adding canvas to the layout
        # adding push button to the layout
        # setting layout to the main window
    # action called by thte push button
    def plot(self):
        # random data
        data = [random.random() for i in range(10)]
        # clearing old figure
        # create an axis
        ax = self.figure.add_subplot(111)
        # plot data
        ax.plot(data, '*-')
        # refresh canvas
# driver code
if __name__ == '__main__':
    # creating apyqt5 application
    app = QApplication(sys.argv)
    # creating a window object
    main = Window()
    # showing the window
    # loop

Also, the keyboard shortcuts are toggles. If you hold down ‘p’, it’ll just enable&disable rapidly.

Keyboard shortcuts are registered by the FigureManager; if you are embedding the FigureCanvas directly, you won’t have one, and will have to register shortcuts yourself.