Interactive figures#
Interactivity can be invaluable when exploring plots. The pan/zoom andmouse-location tools built into the Matplotlib GUI windows are often sufficient, butyou can also use the event system to build customized data exploration tools.
See also
Matplotlib ships withbackends binding toseveral GUI toolkits (Qt, Tk, Wx, GTK, macOS, JavaScript) and third partypackages provide bindings tokivy andJupyter Lab. For the figures to be responsive tomouse, keyboard, and paint events, the GUI event loop needs to be integratedwith an interactive prompt. We recommend using IPython (seebelow).
Thepyplot module provides functions for explicitly creating figuresthat include interactive tools, a toolbar, a tool-tip, andkey bindings:
pyplot.figureCreates a new empty
Figureor selects an existing figurepyplot.subplotspyplot.gcfGet the current
Figure. If there is current no figure on the pyplot figurestack, a new figure is createdpyplot.gcaGet the current
Axes. If there is current no Axes on the Figure,a new one is created
Almost all of the functions inpyplot pass through the currentFigure /Axes(or create one) as appropriate.
Matplotlib keeps a reference to all of the open figurescreated viapyplot.figure orpyplot.subplots so that the figures will not be garbagecollected.Figures can be closed and deregistered frompyplot individually viapyplot.close; all openFigures can be closed viaplt.close('all').
See also
For more discussion of Matplotlib's event system and integrated event loops:-Interactive figures and asynchronous programming-Event handling and picking
IPython integration#
We recommend using IPython for an interactive shell. In addition toall of its features (improved tab-completion, magics, multiline editing, etc),it also ensures that the GUI toolkit event loop is properly integratedwith the command line (seeCommand prompt integration).
In this example, we create and modify a figure via an IPython prompt.The figure displays in a QtAgg GUI window. To configure the integrationand enableinteractive mode use the%matplotlib magic:
In [1]:%matplotlibUsing matplotlib backend: QtAggIn [2]:importmatplotlib.pyplotasplt
Create a new figure window:
In [3]:fig,ax=plt.subplots()
Add a line plot of the data to the window:
In [4]:ln,=ax.plot(range(5))
Change the color of the line from blue to orange:
In [5]:ln.set_color('orange')
If you wish to disable automatic redrawing of the plot:
In [6]:plt.ioff()
If you wish to re-enable automatic redrawing of the plot:
In [7]:plt.ion()
In recent versions ofMatplotlib andIPython, it issufficient to importmatplotlib.pyplot and callpyplot.ion.Using the% magic is guaranteed to work in all versions of Matplotlib and IPython.
Interactive mode#
Enable interactive mode. | |
Disable interactive mode. | |
Return whether plots are updated after every plotting command. |
Display all open figures. | |
Run the GUI event loop forinterval seconds. |
Interactive mode controls:
whether created figures are automatically shown
whether changes to artists automatically trigger re-drawing existing figures
when
pyplot.show()returns if given no arguments: immediately, or after all of the figures have been closed
If in interactive mode:
newly created figures will be displayed immediately
figures will automatically redraw when elements are changed
pyplot.show()displays the figures and immediately returns
If not in interactive mode:
newly created figures and changes to figures are not displayed until
pyplot.show()is calledpyplot.pause()is calledFigureCanvasBase.flush_events()is called
pyplot.show()runs the GUI event loop and does not return until all the plot windows are closed
If you are in non-interactive mode (or created figures while innon-interactive mode) you may need to explicitly callpyplot.showto display the windows on your screen. If you only want to run theGUI event loop for a fixed amount of time, you can usepyplot.pause.This will block the progress of your code as if you had calledtime.sleep, ensure the current window is shown and re-drawn if needed,and run the GUI event loop for the specified period of time.
The GUI event loop being integrated with your command prompt andthe figures being in interactive mode are independent of each other.If you try to usepyplot.ion without arranging for the event-loop integration,your figures will appear but will not be interactive while the prompt is waiting for input.You will not be able to pan/zoom and the figure may not even render(the window might appear black, transparent, or as a snapshot of thedesktop under it). Conversely, if you configure the event loopintegration, displayed figures will be responsive while waiting for inputat the prompt, regardless of pyplot's "interactive mode".
No matter what combination of interactive mode setting and event loop integration,figures will be responsive if you usepyplot.show(block=True),pyplot.pause, or runthe GUI main loop in some other way.
Warning
UsingFigure.show, it is possible to display a figure onthe screen without starting the event loop and without being ininteractive mode. This may work (depending on the GUI toolkit) butwill likely result in a non-responsive figure.
Default UI#
The windows created bypyplot have an interactive toolbar with navigationbuttons and a readout of the data values the cursor is pointing at.
Interactive navigation#

All figure windows come with a navigation toolbar, which can be usedto navigate through the data set.



- The
Home,ForwardandBackbuttons These are similar to a web browser's home, forward and back controls.
ForwardandBackare used to navigate back and forth betweenpreviously defined views. They have no meaning unless you have alreadynavigated somewhere else using the pan and zoom buttons. This is analogousto trying to clickBackon your web browser before visiting anew page orForwardbefore you have gone back to a page --nothing happens.Hometakes you to thefirst, default view of your data.

- The
Pan/Zoombutton This button has two modes: pan and zoom. Click the
Pan/Zoombuttonto activate panning and zooming, then put your mouse somewhereover an axes. Press the left mouse button and hold it to pan thefigure, dragging it to a new position. When you release it, thedata under the point where you pressed will be moved to the pointwhere you released. If you press 'x' or 'y' while panning themotion will be constrained to the x or y axis, respectively. Pressthe right mouse button to zoom, dragging it to a new position.The x axis will be zoomed in proportionately to the rightwardmovement and zoomed out proportionately to the leftward movement.The same is true for the y axis and up/down motions (up zooms in, down zooms out).The point under your mouse when you begin the zoom remains stationary, allowing you tozoom in or out around that point as much as you wish. You can use themodifier keys 'x', 'y' or 'CONTROL' to constrain the zoom to the xaxis, the y axis, or aspect ratio preserve, respectively.With polar plots, the pan and zoom functionality behavesdifferently. The radius axis labels can be dragged using the leftmouse button. The radius scale can be zoomed in and out using theright mouse button.

- The
Zoom-to-Rectanglebutton Put your mouse somewhere over an axes and press a mouse button. Define a rectangular region bydragging the mouse while holding the button to a new location. When usingthe left mouse button, the axes view limits will be zoomed to the definedregion. When using the right mouse button, the axes view limits will bezoomed out, placing the original axes in the defined region.

- The
Subplot-configurationbutton Use this button to configure the appearance of the subplot.You can stretch or compress the left, right, top, or bottomside of the subplot, or the space between the rows orspace between the columns.

- The
Savebutton Click this button to launch a file save dialog. You can savefiles with the following extensions:
png,ps,eps,svgandpdf.
Navigation keyboard shortcuts#
A number of helpful keybindings are registered by default. The following tableholds all the default keys, which can be overwritten by use of yourmatplotlibrc.
Command | Default key binding and rcParam |
|---|---|
Home/Reset |
|
Back |
|
Forward |
|
Pan/Zoom |
|
Zoom-to-rect |
|
Save |
|
Toggle fullscreen |
|
Toggle major grids |
|
Toggle minor grids |
|
Toggle x axis scale (log/linear) |
|
Toggle y axis scale (log/linear) |
|
Close Figure |
|
Constrain pan/zoom to x axis | holdx when panning/zooming with mouse |
Constrain pan/zoom to y axis | holdy when panning/zooming with mouse |
Preserve aspect ratio | holdCONTROL when panning/zooming with mouse |
Other Python prompts#
Interactive mode works in the default Python prompt:
>>>importmatplotlib.pyplotasplt>>>plt.ion()>>>
However, this does not ensure that the event hook is properly installedand your figures may not be responsive. Please consult thedocumentation of your GUI toolkit for details.
Jupyter Notebooks / JupyterLab#
To get interactive figures in the 'classic' notebook or Jupyter lab,use theipympl backend(must be installed separately) which uses theipywidget framework.Ifipympl is installed use the magic:
%matplotlib widget
to select and enable it.
If you only need to use the classic notebook (i.e.notebook<7), you can use
%matplotlib notebook
which uses thebackend_nbagg backend provided by Matplotlib;however, nbagg does not work in Jupyter Lab.
Note
To get the interactive functionality described here, you must beusing an interactive backend. The default backend in notebooks,the inline backend, is not.ipykernel.pylab.backend_inlinerenders the figure once and inserts a static image into thenotebook when the cell is executed. Because the images are static, theycannot be panned / zoomed, take user input, or be updated from othercells.
GUIs + Jupyter#
You can also use one of the non-ipympl GUI backends in a Jupyter Notebook.If you are running your Jupyter kernel locally, the GUI window will spawn onyour desktop adjacent to your web browser. If you run your notebook on a remote server,the kernel will try to open the GUI window on the remote computer. Unless you havearranged to forward the xserver back to your desktop, you will not be able tosee or interact with the window. It may also raise an exception.
PyCharm, Spyder, and VSCode#
Many IDEs have built-in integration with Matplotlib, please consult theirdocumentation for configuration details.