The following does not work:
However this totally works in Jupiter Notebook.
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)
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.
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.
%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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With