%matplotlib line magic causes SyntaxError in Python script - python

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

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.

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

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.

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')

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

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.

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')

Related

matplotlib inline syntax error

I'm testing a python program, which contains calling for IPython. But I got errors in the following code:
If I use
%matplotlib inline
I got a syntax error at the "%" symbol.
I found a solution to this problem using:
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
I got error saying:
AttributeError: 'NoneType' object has no attribute 'run_line_magic'
I'm using Ubuntu 16.04 and running the code via command line. How can I fix this ?
This %matplotlib magic is used to display graphs (of matplotlib.pyplot objects). This needs UI to display. So cannot be display on command prompt.
According to IPython documentation,
If the %matplotlib magic is called without an argument, the output of a plotting command is displayed using the default matplotlib backend in a separate window. Alternatively, the backend can be explicitly requested using, for example:
%matplotlib gtk
A particularly interesting backend, provided by IPython, is the inline backend. This is available only for the Jupyter Notebook and the Jupyter QtConsole. It can be invoked as follows:
%matplotlib inline
Simple solution would be to replace %matplotlib inline with %matplotlib and run it using ipython.
Alternatively, what you could do is download jupyter notebook and run that code there.
Or as #tihom said in comments, you could comment or remove that line and run the code but this wouldn't display the graphs and other things.
You can use pylab mode in ipython. Simply run ipython --pylab in the terminal. That will launch ipython configured to be able to support the matplotlib GUI backend

%matplotlib linline produces error

I have the following code which is regular for anyone who would like to make a plot with pandas in IPython.
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import matplotlib.pyplot as plt
In [4]: %matplotlib inline
Here it pops up an error:
UsageError: Invalid GUI request u'inline', valid ones are: pyglet, osx, qt5, qt, glut, gtk, gtk3, tk, wx
I read this post Run python script in IPython with inline / embedded plots
and found the two methods to get around:
ipython qtconsole --matplotlib inline -m example_plots
or
ipython qtconsole --pylab inline -m example_plots
But none of them works in my situation (I actually got stuck in iPython without making a plot, needless to say a plot embedded within a script.)
I am not sure where went wrong as %matplotlib inline used to work. I am using python 2.7.11 and IPython 4.2.0 if this information helps.
Thank you very much for your help.

Jupyter Notebook ImportError, %matplotlib qt

I am using
%matplotlib inline
to display plots inside the notebook. I would like to disable this for several cells. So, I try
%matplotlib qt
This outputs the following error:
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
I am not sure how to solve this, as everything is up to date.
How can I solve the above?
Is there another way to disable %matplotlib inline in a certain cell without restarting the entire kernel?
You might be able to use plt.switch_backend, although as the documentation states, this is an experimental feature. The following works for me, using matplotlib 1.5 and an IPython 4.0.1:
In [1]: from matplotlib import pyplot as plt
In [2]: import numpy as np
# plot appears inline (default)
In [3]:plt.plot(np.random.randn(10))
Out[3]:[<matplotlib.lines.Line2D at 0x7fac4408e390>]
In [4]: plt.switch_backend('QtAgg4')
# plot appears inside a separate Qt4 window
In [5]:plt.plot(np.random.randn(10))
Out[5]:[<matplotlib.lines.Line2D at 0x7fac3b408a90>]
You might need to change 'QtAgg4' according to whichever version of PyQt you have installed - this could be the cause of the error you mentioned in the question. Another interactive backend that should work on Mac would be 'CocoaAgg'. If the images are very large you could also use the 'Agg' backend to suppress plotting altogether, and instead save the resulting figure(s) straight to disk.
If you don't have a specific backend installed use "agg":
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
Reference: https://github.com/matplotlib/matplotlib/issues/9017

plot() doesn't work on IPython notebook

I'm new to python scientific computing, and I tried to make a simple graph on IPython notebook.
import pandas
plot(arange(10))
Then error had shown as below.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-6b139d572bd6> in <module>()
1 import pandas
----> 2 plot(arange(10))
NameError: name 'plot' is not defined
Instead, with IPython --pylab mode, a right graph popped up when I tried the same code.
Am I missing any environment?
My environment is Mac OSX 10.8.5, python 2.7.5, IPython 1.1.0, matplotlib 1.3.1, and pandas 0.12.0. I downloaded python scientific environment by Anaconda installer from continuum.io. Anaconda version is the newest one as of 1/30/2014.
It is not advisable to use pylab mode. See the following post from Matthias Bussonnier
A summary from that post:
Why not to use pylab flag:
It is irreversible- Cannot unimport
Unclear- if someone else did not run with this flag (or with a different setting of it) what would happen?
Pollutes the namespace
Replaces built-ins
Side effects
You are much better by doing the following inside your IPython notebook.
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(range(10))
The following is the code which --pylab brings into the namespace
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
Still, if you wish to use pylab and have plots inline, you may do either of the following:
From shell:
$ ipython notebook --pylab inline
Or, from within your notebook
%pylab inline

Configuration of Ipython

I'm new to python and Ipython. I'm following the data analysis with pandas on youtube. the link
I installed Anaconda and then started to use Ipython on Windows 8.1
For several commands, it seems OK
In [2]: print 5
5
But when I tried to followe the tutorial online it seems that my Ipyhon has got some problems,
In [3]: %pylib inline
ERROR: Line magic function `%pylib` not found.
Also, I just copies the code from the tutorials, just very simple codes like this
In [4]:plot(arange(10))
NameError Traceback (most recent call last)
<ipython-input-6-353c92d67d6b> in <module>()
----> 1 plot(arange(10))
NameError: name 'plot' is not defined
After "imported matplotlib", it still didn't work.
Also, the code a = arange(10) didn't work. I have to use it like this:
import numpy as np
a = np.arange(10)
But the tutor in this video didn't use it like this.
I think it should be associated with the configuration with anaconda or Ipython?
But I'm not sure about this and I don't know how to figure it out. I'm using the latest version of anaconda on windows 64bit.
Any suggestions? Thanks!
use %pylab inline or %pylab to enable pylab mode. This will alter the event loop either to show plots inline (notebook) or to display them in different window without interfering the code execution (CLI).
Executing %pylab will set ipython to handle matplotlib nicely, and will also commit from pylab import * that will put numpy and matplotlib commands inside your default namespace.
equivalent way to that, when you invoke IPython, use `ipython --pylab [notebook|qtconsole|etc..]. In windows, you can either do that from console or alter a shortcut to add command line arguments.
You can change IPython system wide configuration to load pylab, see http://ipython.org/ipython-doc/stable/config/overview.html#flags
See this answer for more information: https://stackoverflow.com/a/21457629/3245308

Categories