Interactive mode in matplotlib in Python
The topic of this tutorial is Interactive mode in matplotlib in Python.
The interactive mode in the matplotlib library is one of the useful available features. It can be handy if one needs to plot different kinds of plots. Sometimes we need to zoom a plot to see some intersections more clearly or we need to save a plot for future use. All these things are possible and easy with the matplotlib interactive environment. In this tutorial, we are going to see, how we can enable the matplotlib interactive environment.
Interactive mode in Jupyter Notebook
To enable the interactive mode in the jupyter notebook, you need to run the following magic function before every plot you make.
%matplotlib notebook
After calling the function, import the matplotlib library as usual and start making a plot.
Let us take an example from a previous article on how to make a line plot, link: Line Chart Plotting in Python using Matplotlib
To make this plot interactive, run the following code.
%matplotlib notebook import matplotlib.pyplot as plt X1 = [1,2,3,4,5] Y1 = [2,4,6,8,10] plt.plot(X1, Y1, label = "plot 1") X2 = [1,2,3,4,5] Y2 = [1,4,9,16,25] plt.plot(X2, Y2, label = "plot 2") plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Two plots on the same graph') plt.legend()
Output:
As you can see in the output above there are some buttons associated with the plot.
Hover over the buttons to find what that button does. You can also resize the plot and save a plot using these buttons.
See the following image as a reference.
Some points to remember
- Always call the magic function before importing the matplotlib library.
- Run the magic function before every plot you make otherwise it will overwrite the previous plot.
- You can otherwise end the interaction using the end interaction button and then make a new plot. By doing this you don’t need to call the magic function again for a new plot.
- If you don’t end the interactive plot it can give weird bugs in the following cells.
I hope you liked the article. Comment if you have any doubts or suggestions regarding this article.
Leave a Reply