What is Matplotlib inline in Python

In this Python tutorial, we will discuss what is matplotlib inline in Python, and we will also cover the following topics:

  • What is matplotlib inline in python
  • Why matplotlib inline is used
  • How to use matplotlib inline
  • matplotlib inline jupyter
  • matplotlib inline in pycharm
  • matplotlib inline in spyder
  • matplotlib inline in vscode
  • matplotlib inline vs notebook

What is matplotlib inline in python

IPython provides a collection of several predefined functions called magic functions, which can be used and called by command-line style syntax. Basically, there are two types of magic functions, line-oriented and cell-oriented.

  • Line-oriented magic functions (also called line magics) start with a percentage sign (%) followed by the arguments in the rest of the line without any quotes or parentheses, as same as an OS command-line calling of a function. These functions return some result hence can be stored by writing it on the right-hand side of an assignment statement.

Some line magics: %alias, %autowait, %colors, %conda, %config, %debug, %env, %load, %macro, %matplotlib, %notebook, etc.,

  • Cell-oriented magic functions (also called cell magics) start with two percentage signs (%%) followed by the arguments in the whole cell, that is in the rest of the line and also lines below it in a separate argument.

Some cell magics: %%bash, %%html, %%javascrit, %%python2, %%ruby, %%sh, %%script, %%perl, etc.,

Now, tet’s talk about the %matplotlib magic function: This function sets up the matplotlib to work interactively. It lets you activate the matplotlib interactive support anywhere in an IPython session (like in jupyter notebook). The syntax to call this function is given below:

%matplotlib [gui]

In the above syntax:

  • gui is the name of the matplotlib backend to be enabled by calling the function.
  • It provide the backends: inline, notebook, qt, qt4, qt5, tk, osx, pdf, etc.,

You can list the available matplotlib backends by:

%matplotlib -l

# OR

%matplotlib --list

When you enable the ‘inline’ matplotlib backend, the output of the plotting commands written will be displayed inline within the frontends like jupyter notebook. It means, the plot/graph will be displayed directly below the cell (where the plotting commands are written) and the resulted plot/graph will also be included (stored) in your notebook document.

Read: How to install matplotlib python

Why matplotlib inline is used

You can use the magic function %matplotlib inline to enable the inline plotting, where the plots/graphs will be displayed just below the cell where your plotting commands are written.

It provides interactivity with the backend in the frontends like the jupyter notebook. It also provides the feature where, the plotting commands below the output cell of the previous plot, will not affect the previous plot, which means it separates different plots.

For example, changing the color palette by colormap in the cell below the previous plot output cell will not change the colormap of that plot.

NOTE – If you are not in the interactive mode and using matplotlib for plotting graphs, then the graph will only appear if you call the matplotlib.pyplot.show() function in previous versions of jupyter notebook.

In the current versions of the IPython notebook and jupyter notebook, it is not necessary to use the %matplotlib inline function. As, whether you call matplotlib.pyplot.show() function or not, the graph output will be displayed in any case.

Read Matplotlib savefig blank image

How to use matplotlib inline

Write %matplotlib inline at the start of the cell before plotting commands in your notebook (jupyter notebook).

%matplotlib inline
...
...                  # Plotting commands
...

Example :

from matplotlib import pyplot as plt
import numpy as np


%matplotlib inline

x = np.arange(-10, 10, 1)
y = np.sin(x)

plt.title('%matplotlib inline function's magic')
plt.plot(x, y, 'b:')
How to use matplotlib inline
How to use matplotlib inline

Read: Matplotlib plot a line

matplotlib inline jupyter

We have discussed the use of the %matplotlib inline function in jupyter in the above topic. It is the same as we discussed there.

So, let’s practice an example to make the concepts more clear.

from matplotlib import pyplot as plt
import numpy as np


%matplotlib inline

x = np.arange(-10, 10, 1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

plt.figure(figsize=[9, 7])

plt.title('%matplotlib inline function\'s magic', fontsize=18)
plt.plot(x, y1, 'r--', linewidth=2, label='sin()')
plt.plot(x, y2, 'b-.', linewidth=2, label='cos()')
plt.plot(x, y3, 'g:', linewidth=2, label='tan()')

plt.axvline(x=0, color='black')
plt.axhline(y=0, color='black')

plt.xlabel('x-axis', fontsize=15)
plt.ylabel('y-axis', fontsize=15)
plt.legend(fontsize=15)
matplotlib inline jupyter
matplotlib inline jupyter

matplotlib inline in pycharm

Matplotlib plots do not display in Pycharm.

The % notation is for using the magic functions available in python, and %matplotlib inline, represents the magic function %matplotlib, which specifies the backend for matplotlib, and with the argument inline you can display the graph and make the plot interactive.

But %matplotlib inline is only meant for the IPython notebook session, if used in a normal python session (like in pycharm), you will get the syntax error.

You can display your plot in a normal python session for an interactive window by using matplotlib.pyplot.show() function.

Read: Python plot multiple lines

matplotlib inline in spyder

As we have discussed in the above topic, the %matplotlib inline does not work within a script and in normal python sessions (like pycharm, spyder, etc.,), works only in the IPython notebook sessions.

There can be two methods through which you can import the feature of the %matplotlib inline function:

  • You can import the IPython and use the magic function %matplotlib inline. Follow the code below to do so:
from IPython import get_ipython

get_ipython().run_line_magic('matplotlib', 'inline')

Example :

from matplotlib import pyplot as plt
import numpy as np

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')


x = np.linspace(1, 100, 2)
y = np.sin(x)

plt.title('matplotlib inline in spyder')
plt.plot(x, y, 'c:')
matplotlib inline in spyder
matplotlib inline in spyder
  • You can set the graphics backend to inline or automatic in the spyder as given below:
    • Navigate through: Tools >> Preferences >> IPython console >> Graphics -> Inline/Automatic
    • Then, restart the console, now you will be able to plot the graph and display it in the interactive window by using the get_ipython() command, without restarting the console.
matplotlib inline in spyder automatically
matplotlib inline in spyder automatically

Read: modulenotfounderror: no module named ‘matplotlib’

matplotlib inline in vscode

Visual Studio Code also provides a normal python session in which you can not use the %matplotlib inline function.

  • However, you can install and use the jupyter notebook extension available for the vscode where you can write code like in jupyter notebook and can use the %matplotlib inline command. And, using this magic function will be as same as we have done in jupyter notebook.
jupyter notebook extension for vscode
Jupyter Notebook extension for vs code

Example :

from matplotlib import pyplot as plt
import numpy as np


x = np.linspace(1, 100, 2)
y = 0.2 * x + 3

%matplotlib inline

plt.title('matplotlib inline in vscode')
plt.plot(x, y, 'o:')
matplotlib inline in jupyter notebook extension for vscode
matplotlib inline in jupyter notebook extension for vs code
  • Or you can use the vscode in interactive mode, it splits your code into separate cells that can be run separately as same as in an IPython notebook. You can split your code into separate cells by using the # %%, which tells the vscode to separate the following code from the above. When you run your code this way, vscode automatically opens an interactive window to display the plots inline.

Example :

# $$
from matplotlib import pyplot as plt
import numpy as np

# $$
x = np.linspace(1, 100, 2)
y = 0.1 * x + 2

plt.title('matplotlib inline in vscode')
plt.plot(x, y, color='green', linestyle=':')
plt.show()
matplotlib inline in vscode
matplotlib inline in vscode

Read: Python sort list of tuples

matplotlib inline vs notebook

When you want to add a plot in your IPython notebook (jupyter notebook), then you can use the magic function %matplotlib with different arguments according to the need. Arguments can be inline, notebook, qt, etc., which will open the figure in a window.

%matplotlib inline: You can use this command to display the plots (static plots) in line with the code.

from matplotlib import pyplot as plt
import numpy as np


%matplotlib inline

x = np.arange(-10, 11, 1)
y1 = np.square(x)
y2 = np.power(x, 3)

plt.figure(figsize=[9, 7])
plt.title('%matplotlib inline function\'s magic', fontsize=18)
plt.plot(x, y1, 'r--', label='x^2')
plt.plot(x, y2, 'b-.', label='x^3')

plt.axvline(x=0, color='black', linewidth=0.7)
plt.axhline(y=0, color='black', linewidth=0.7)

plt.xlabel('x-axis', fontsize=15)
plt.ylabel('y-axis', fontsize=15)
plt.legend(fontsize=15)
matplotlib inline vs notebook
matplotlib inline vs notebook

%matplotlib notebook: You can use this command to display the plots in an interactive window, where you can zoom, or resize the figure.

NOTE – New versions of IPython notebook do not support %matplotlib notebook and returns an error: Javascript Error: IPython is not defined.

You can use an alternative for that to display interactive graphs, which we will discuss in another post.

You also like reading our latest articles.

In this Python tutorial, we have discussed the %matplotlib inline in matplotlib, and we have also covered the following topics:

  • What is matplotlib inline in python
  • Why matplotlib inline is used
  • How to use matplotlib inline
  • matplotlib inline jupyter
  • matplotlib inline in pycharm
  • matplotlib inline in spyder
  • matplotlib inline in vscode
  • matplotlib inline vs notebook