ZHU
ZHU

Reputation: 986

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)

Upvotes: 15

Views: 40029

Answers (3)

HuynhTan
HuynhTan

Reputation: 51

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

Upvotes: 5

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

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.

Upvotes: 16

numbermaniac
numbermaniac

Reputation: 788

According to http://ipython.readthedocs.io/en/stable/interactive/magics.html, % is a special iPython/Jupyter command:

Define an alias for a system command.

%alias alias_name cmd defines alias_name as an alias for cmd

In standard Python, % takes the remainder when one number is divided by another (or can be used for string interpolation), so in a standard Python program, %matplotlib inline doesn't make any sense. It does, however, work in iPython, as described above.

Upvotes: 3

Related Questions