Render Interactive plots with Matplotlib | by Parul Pandey | Towards Data Science

Good charts effectively convey information. Great charts enable, inform, and improve decision making.” — Dante Vitagliano
Interactive charts are loved by all as they can tell a story more effectively. The same is true in data science and allied fields. Exploratory data analysis is an essential step in the data preprocessing pipeline, and there are a lot of libraries available in the ecosystem to achieve that. The graphic below beautifully encapsulates this idea.
Even with so many choices, Matplotlib , fondly known as the Grandfather of python visualization packages remains a favorite for many. The lack of interactiveness, however, remains a bottleneck. So, workarounds have been devised to include interactivity via some third-party libraries. But did you know that it is also possible to create interactive plots with matplotlib directly, provided you are using an interactive backend? This article will look at two such backends and how they render interactivity within the notebooks, using only matplotlib.
Matplotlib caters to different users and hence supports various backends. As per the documentation:
the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure.
This means the pre-requisite for interactivity is having an interactive backend. The default backend in the Jupyter notebooks is the inline backend which is enabled by %matplotlib inline.It is great at rendering static images but offers no interactive features like pan, zoom, or auto-updating the figures from other cells.
On the contrary, there are backends which when enabled, render interactive images. This article will go over the two common ones and so that you can use them in your data visualization tasks.
The backend_nbagg renders interactive figures in a notebook. It makes use of the infrastructure developed for the webagg backend.
Enabling the backend
To enable the backend in the Jupyter notebook, type the following
%matplotlib notebook
Usage
Here is an elementary example to showcase the usage of the nbagg backend.
# The code is to be run in a Jupyter Notebookimport matplotlib.pyplot as plt%matplotlib notebookplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45], linewidth = 3, c = 'g')
It is also possible to auto-update the figure from other cells. For instance, the line chart can be updated via the code executed in the subsequent cells in the figure below.
This functionality can be switched off easily with a blue button 🔵 provided on the right-hand side corner. When clicked, the interaction will stop, and a new plot will be generated in the next cell. It's that simple.
The interactivity is not only limited to 2D plots but can also be observed in 3D plots. The code has been taken from matplotlib's official documentation.
# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import axes3d%matplotlib notebookfig = plt.figure()ax = fig.add_subplot(111, projection='3d')# Grab some test data.X, Y, Z = axes3d.get_test_data(0.05)# Plot a surface plot.ax.plot_surface(X, Y, Z, rstride=10, cstride=10, )plt.show()
This option works well and gets our work done, but it is not compatible with Jupyter Lab. As a result, it isn't of much use for the Jupyter Lab users. Also, the save option doesn’t seem to work for me. There is a better alternative to achieve the same results, albeit with a different backend.
The ipyml backend renders interactive figures in the 'classic' notebook as well as the Jupyter lab. The ipyml backend uses the ipywidget framework and needs to be installed separately. Widgets are used to build interactive GUIs right in the notebook environment. With the help of controls like a slider, textbox, etc., users can seamlessly interact with their visualizations.
Ipympl's can be easily installed with pip or conda. Refer to the documentation for more details.
pip install ipymplor conda install -c conda-forge ipympl
For Jupyter Lab users, node js and jupyterLab extension manager are also required. For a better experience, it is recommended to use JupyterLab >= 3.
conda install -c conda-forge nodejsjupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter-matplotlib
Enabling the backend
To be able to use the ipyml backend, one needs to type the following :
%matplotlib widget
Now that we have fulfilled all the requirements, it's time for the demo.
We'll use the same example as we used in the last section. This will also help us to compare the two functionalities.
# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as plt%matplotlib widgetplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45])
The ipyml backend also works for the 3D visualizations.
The controls, in this case, lie on the right side of the figure but other than that, it is pretty similar to the plot obtained in the last section. That is true, but there are some subtle differences, in case you have noticed:
Plots can be saved as static images.
The plot widget can be resized by the UI.
This is a great feature that I haven't seen in most of the other visualization libraries.
The ipyml backend enables interactivity in matplotlib and all the libraries built on top of matplotlib like Pandas, Geopandas, Seaborn, etc.
Here is a summary of what we covered in this article. We learnt about a few of the matplotlib's backends and learnt about the ones that enable interactivity. Both nbagg and ipyml seem to work great, but ipyml has additional features that are preferable. I'm sure you'll like to experiment with these backends and see the interactive features for yourself. If you liked this article, I believe you'll also like few other pieces that I wrote involving matplotlib directly or indirectly.
In case you want to use the matplotlib library to create some engaging animations.
towardsdatascience.com
A tutorial on creating Plotly and Bokeh plots directly with Pandas plotting syntax
towardsdatascience.com
Some of the advanced plots in matplotlib, which can take our analysis a notch higher.