Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't '%matplotlib inline' work in python script?

The following does not work:

enter image description here

However this totally works in Jupiter Notebook.

enter image description here

If I simply comment it out, the graph doesn't show up. (Maybe it won't show up anyways)

import pandas as pd
import matplotlib

from numpy.random import randn
import numpy as np

import matplotlib.pyplot as plt

df = pd.read_csv('data/playgolf.csv', delimiter='|' )
print(df.head())

hs = df.hist(['Temperature','Humidity'], bins=5)
print(hs)
like image 437
ZHU Avatar asked May 28 '17 07:05

ZHU


People also ask

How do I inline a matplotlib in Python?

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.

Is matplotlib inline still needed?

So %matplotlib inline is only necessary to register this function so that it displays in the output. Running import matplotlib. pyplot as plt also registers this same function, so as of now it's not necessary to even use %matplotlib inline if you use pyplot or a library that imports pyplot like pandas or seaborn.

How does matplotlib inline work?

%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

What is the error in %Matplotlib inline?

In []: %matplotlib inline. Since this is not a valid python code, if we include it inside a python script it will return with a syntax error (even when the script is executed from Jupyter notebook using import or other mechanism).


2 Answers

Other answers and comments have sufficiently detailed why %matplotlib inline cannot work in python scripts.

To solve the actual problem, which is to show the plot in a script, the answer is to use

plt.show()

at the end of the script.

like image 117
ImportanceOfBeingErnest Avatar answered Oct 15 '22 09:10

ImportanceOfBeingErnest


If you are using notebook and run my_file.py file as a module

Change the line "%matplotlib inline" to "get_ipython().run_line_magic('matplotlib', 'inline')". Then run my_file.py using this %run It should look like this:

In my_file.py:

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

In notebook:

%run my_file.py

This run my_file.py in ipython, which help avoid the bug

NameError: name 'get_ipython' is not defined

like image 37
HuynhTan Avatar answered Oct 15 '22 11:10

HuynhTan