[python] %matplotlib line magic causes SyntaxError in Python script

I try to run the following codes on Spyder (Python 2.7.11):

# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd

%matplotlib inline

import matplotlib.pyplot as plt
import matplotlib.cm as cm

import tensorflow as tf

# settings
LEARNING_RATE = 1e-4
# set to 20000 on local environment to get 0.99 accuracy
TRAINING_ITERATIONS = 2000        

DROPOUT = 0.5
BATCH_SIZE = 50

# set to 0 to train on all available data
VALIDATION_SIZE = 2000

# image number to output
IMAGE_TO_DISPLAY = 10

But I got this error:

line 10
    %matplotlib inline
    ^
SyntaxError: invalid syntax.

I appreciate if anybody gives me an explanation.

P.S. the code is from Kaggle competition project: Digit Recognizer

This question is related to python matplotlib ipython spyder

The answer is


If you include the following code at the top of your script, matplotlib will run inline when in an IPython environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib won't run inline, and the charts will open in a pop-ups as usual).

from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')

Instead of %matplotlib inline,it is not a python script so we can write like this it will work from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline')


There are several reasons as to why this wouldn't work.

It is possible that matplotlib is not properly installed. have you tried running:

conda install matplotlib

If that doesn't work, look at your %PATH% environment variable, does it contain your libraries and python paths?

Similar problem on github anaconda


The syntax '%' in %matplotlib inline is recognized by iPython (where it is set up to handle the magic methods), but not Python itself, which gives a SyntaxError. Here is given one solution.


Because line magics are only supported by the IPython command line not by Python cl, use: 'exec(%matplotlib inline)' instead of %matplotlib inline


This is the case you are using Julia:

The analogue of IPython's %matplotlib in Julia is to use the PyPlot package, which gives a Julia interface to Matplotlib including inline plots in IJulia notebooks. (The equivalent of numpy is already loaded by default in Julia.) Given PyPlot, the analogue of %matplotlib inline is using PyPlot, since PyPlot defaults to inline plots in IJulia.


Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something is not correct Python syntax.

If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic function.

Instead of %matplotlib inline, you will have to do something like this in your script:

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

A similar approach is described in this answer, but it uses the deprecated magic function.

Note that the script still needs to run in IPython. Under vanilla Python the get_ipython function returns None and get_ipython().run_line_magic will raise an AttributeError.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to matplotlib

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to increase image size of pandas.DataFrame.plot in jupyter notebook? How to create a stacked bar chart for my DataFrame using seaborn? How to display multiple images in one figure correctly? Edit seaborn legend How to hide axes and gridlines in Matplotlib (python) How to set x axis values in matplotlib python? How to specify legend position in matplotlib in graph coordinates Python "TypeError: unhashable type: 'slice'" for encoding categorical data Seaborn Barplot - Displaying Values

Examples related to ipython

How to increase image size of pandas.DataFrame.plot in jupyter notebook? Importing .py files in Google Colab Selection with .loc in python IOPub data rate exceeded in Jupyter notebook (when viewing image) Purpose of "%matplotlib inline" Installing a pip package from within a Jupyter Notebook not working convert json ipython notebook(.ipynb) to .py file In which conda environment is Jupyter executing? How to make inline plots in Jupyter Notebook larger? %matplotlib line magic causes SyntaxError in Python script

Examples related to spyder

Anaconda Navigator won't launch (windows 10) How to start Spyder IDE on Windows How to change python version in anaconda spyder Python Pandas - Missing required dependencies ['numpy'] 1 how to update spyder on anaconda How to change the Spyder editor background to dark? Shortcut key for commenting out lines of Python code in Spyder ImportError: No module named 'google' %matplotlib line magic causes SyntaxError in Python script How to run Spyder in virtual environment?