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
Related
I'm trying out Jupyter console for the first time, but can't get the %matplotlib inline magic to work. Below is a screenshot of an example session:
The plot shows in a separate window after I run Line 6, and Line 7 doesn't do anything.
When I run %matplotlib --list, inline is given as one of the options:
Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt',
'nbagg', 'agg', 'gtk', 'tk', 'ipympl', 'inline']
When I try to use another backend, say qt5, it gives an error message because I don't have any Qt installed.
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, or PySide
package to be installed, but it was not found.
Running %matplotlib?? reads:
If you are using the inline matplotlib backend in the IPython Notebook
you can set which figure formats are enabled using the following::
In [1]: from IPython.display import set_matplotlib_formats
In [2]: set_matplotlib_formats('pdf', 'svg')
The default for inline figures sets `bbox_inches` to 'tight'. This can
cause discrepancies between the displayed image and the identical
image created using `savefig`. This behavior can be disabled using the
`%config` magic::
In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
But I don't know if it's something I can tweak around to solve my issue.
When I try it the magic IPython console, it says inline is an Unknown Backend.
UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt,
qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx
I've also found this issue on github after some googling but I don't even know if it's relevant to my situation (most of their conversation didn't make sense to me lol).
Lastly, I'm not sure if this issue is related at all, but here it is, just in case: when I try to open Vim in Jupyter via the !vim command, it glitches pretty badly, preventing me from even exiting out of Jupyter itself without closing the terminal altogther. Vim works perfectly fine when called inside IPython console, however.
I'm using matplotlib 2.0.0.
If anyone could help me figure this out, that'd be great! Thank you!
You’re running a console which is completely text based and incapable of showing images. Therefore, although inline is available, it's not producing inline output.
I'm not sure why it doesn't throw an error, though, which it does in my case:
You can use %matplotlib inline in a GUI console, like Jupyter QTConsole
or in a jupyter notebook in the browser
%matplotlib without the inline works for me (I'm using osx and IPython 7.0.1)
If you're running an old version of ipython try %pylab inline instead. See notes in this tutorial
In my Jupyter notebook I am now using %matplotlib notebook instead of %matplotlib inline, it's awesome that I can now interact with my plots on Jupyter. However, when I try to make an histogram I get a blank plot:
If I use %matplotlib inline everything works fine:
What's going on?
Seeing that my comment above has indeed helped someone to solve the problem I will post it as an answer.
The problem occurs if you switch from %matplotlib inline to %matplotlib notebook without restarting the kernel.
Switching from %matplotlib notebook to %matplotlib inline works fine.
So the solution is to either restart the kernel or start a new notebook.
It seems that in some cases it helps to repeat the setting of the notebook backend, i.e. call it twice like
%matplotlib notebook
%matplotlib notebook
An analysis for why that is can be found in this comment
The answer is not necessarily to restart the entire kernel.
If you reload the matplotlib module, it will work, too. Provided you use Python 3.6 like me, and you have import matplotlib.pyplot as plt like me:
from importlib import reload
reload(plt)
%matplotlib notebook
It does the trick. Yes it is still a hack. At least this is an independent codecell you can use in the middle of the notebook. Switching back via %matplotlib inline is not a problem.
You can also remove once imported names from the sys.modules list, then they get imported again when you call the import again.
import sys
sys.modules.pop('matplotlib')
from matplotlib import pyplot as plt
In many cases, that's a less good idea. But it might sometimes be the only straw to hold on.
I was able to fix it by downgrading matplotlib to 3.1.3:
conda install matplotlib=3.1.3
I was running version 3.3.2 and had this same issue. I was not switching between %matplotlib inline and %matplotlib notebook, and it did not matter if I placed %matplotlib notebook before or after importing
The issue seems to be an interaction between switching:
%matplotlib notebook
%matplotlib inline
and using the figure "power button" on interactive plots:
Solution: If you pressed the button and are getting blank plots, restart Jupyter and don't use the power button again if you need to switch between notebook and inline
On a new notebook if you start by using %matplotlib notebook then you can switch between that an inline without issue.
I confirm that both restarting of the kernel and the running of the code do the trick!
For me, it also appeared after switching from 'inline' to 'notebook' but restarting the kernel didn't work. I had to go through file > close and halt, and then either reopen it or restart the kernel if the page is still open.
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')
I installed anaconda to use pandas and scipy. I reading and watching pandas tutorials and they all say to open the ipython notebook using
ipython notebook --pylab==inline
but when I do that I get a message saying
"Support for specifying --pylab on the command line has been removed. Please use '%pylab = inline' or '%matplotlib =inline' in the notebook itself"
But that does not work. Then when I try "plot(arange(10))" I get a message saying "name 'plot' is not defined." I trying plotting data from a .csv file and got
"matplotlib.axes._subplots.AxesSubplot at 0xebf8b70".
What should I do?
I believe the pylab magic was removed when they transitioned from IPython to a more general Jupyter notebook.
Try:
%matplotlib inline
Also when you get a message like:
"matplotlib.axes._subplots.AxesSubplot at 0xebf8b70".
That's just IPython displaying the object. You need to specify IPython display it. Hence the matplotlib inline magic.
Setup:
I have an IPython Notebook I’d like to include in the tutorials section of my docs. I’ve written a .ipynb —> .rst conversion script (using pandoc) that works as follows: the notebook is first converted to a .py file, which is executed as a script, and if the script execution raises no exceptions, an .rst export is triggered and a link to that tutorial is built in the appropriate spot of the docs. That way, the tutorials can be integrated into my docs only under the condition that the code does what the tutorial says it does. This method was developed as a result of the following question: Raise exception if script fails
Ok, so here is the problem. I’d like for some of the .ipynb tutorials to include in-line plots with matplotlib. The way I display plots in an IPython Notebook is using the magic function call:
%matplotlib inline
However, if this command appears in a python executable script, python raises an exception. So none of my tutorials can currently include plots.
Question:
So my question is this: how can I include in-line plots in a Notebook in a way that will not raise an exception when the notebook is exported to a .py file and executed as a script? Or, short of that, any suggestions for another workaround?
Use this instead:
from IPython import get_ipython
ipython = get_ipython()
if ipython:
ipython.magic("matplotlib inline")
Currently, there should be no real need to use %matplotlib inline magic in jupyter. Instead, this should display nicely:
import matplotlib.pyplot as plt
fig, ax = plt.subplot(111)
ax.plot([3,4,2,5])
fig