How to make IPython notebook matplotlib plot inline - python

I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.
I cannot get matplotlib graphics to show up inline.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
Instead of inline graphics, I get this:
<matplotlib.figure.Figure at 0x110b9c450>
And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.

I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:
c.IPKernelApp.matplotlib=<CaselessStrEnum>
Default: None
Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
Configure matplotlib for interactive use with the default matplotlib backend.

If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.

Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.

Use the %pylab inline magic command.

To make matplotlib inline by default in Jupyter (IPython 3):
Edit file ~/.ipython/profile_default/ipython_config.py
Add line c.InteractiveShellApp.matplotlib = 'inline'
Please note that adding this line to ipython_notebook_config.py would not work.
Otherwise it works well with Jupyter and IPython 3.1.0

I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):
It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.
See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.

I did the anaconda install but matplotlib is not plotting
It starts plotting when i did this
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)

You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.

If you're using Jupyter notebooks in Visual Studio Code (VSCode) then the inline backend doesn't seem to work so you need to specify widget/ipympl (which you may need to install support for e.g. pip install ipympl):
%matplotlib widget

Related

Dynamically plot instead of %matplotlib notebook in jupyter lab without side effect

I recently used jupyter lab instead of jupyter notebook.
But the following code can't work expectations.
import matplotlib.pyplot as plt
import numpy as np
from tqdm.notebook import tqdm, trange
#%matplotlib widget # For jupyter lab
%matplotlib notebook # For jupyter notebook
plt.ion()
fig, ax = plt.subplots()
xs = []
for i in trange(100):
x = i / 10
xs.append(x)
ax.clear()
ax.plot(xs, np.sin(xs))
fig.canvas.draw()
It works on the jupyter notebook, the plot will update dynamically.
But It doesn't work on the jupyter lab.
Of cause, the magic code of %matplotlib is changed on the individual environment.
By the way, I know another method to plot dynamically.
This method also work jupyter lab.
But this method can't work tqdm because clear_output will clear progress bar too.
How to avoid this problem instead of the above question?
I seem the below question is more simple than the above question.
import matplotlib.pyplot as plt
import numpy as np
from tqdm.notebook import tqdm, trange
from io import BytesIO
import imageio
from IPython.display import Image, display_png, clear_output
#%matplotlib widget
%matplotlib notebook
plt.ion()
fig, ax = plt.subplots()
xs = []
for i in trange(100):
x = i / 10
xs.append(x)
ax.clear()
ax.plot(xs, np.sin(xs))
io = BytesIO()
fig.savefig(io, format='png')
clear_output(wait=True)
display_png(Image(io.getvalue()))
Updated:
The result of the above script is the following gif.
This plot is dynamically rendering while running the script.
(This script is not complitely because the tqdm progress bar is cleared.
the problem is side effect of IPython.display.clear_output.)

Matplotlib FuncAnimation not plotting any chart inside Jupyter Notebook

Simple matplotlib plot. Here is my code
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random
x = []
y = []
index=count()
def animate(i):
x.append(next(index))
y.append(random.randint(0,10))
plt.plot(x,y)
a = FuncAnimation(plt.gcf(),animate,interval=1000)
plt.tight_layout()
plt.show()
Running the code above I get
<Figure size 576x396 with 0 Axes>
but no chart appears.
Are you using Jupyter notebooks to run it? I tried with native libraries and it works just fine. The plots are visible.
Checking here i see the same situation. Could you try to use %matplotlib inline before importing matplotlib as:
%matplotlib inline # this line before importing matplotlib
from matplotlib import pyplot as plt
That said, the animation can be displayed using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.
from IPython.display import HTML
HTML(a.to_jshtml())
this answer brings a more complete overview...

Add text to points in scatterplot from Pandas Dataframe [duplicate]

I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.
I cannot get matplotlib graphics to show up inline.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
Instead of inline graphics, I get this:
<matplotlib.figure.Figure at 0x110b9c450>
And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.
I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:
c.IPKernelApp.matplotlib=<CaselessStrEnum>
Default: None
Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
Configure matplotlib for interactive use with the default matplotlib backend.
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.
Use the %pylab inline magic command.
To make matplotlib inline by default in Jupyter (IPython 3):
Edit file ~/.ipython/profile_default/ipython_config.py
Add line c.InteractiveShellApp.matplotlib = 'inline'
Please note that adding this line to ipython_notebook_config.py would not work.
Otherwise it works well with Jupyter and IPython 3.1.0
I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):
It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.
See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb
I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.
I did the anaconda install but matplotlib is not plotting
It starts plotting when i did this
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)
You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.
If you're using Jupyter notebooks in Visual Studio Code (VSCode) then the inline backend doesn't seem to work so you need to specify widget/ipympl (which you may need to install support for e.g. pip install ipympl):
%matplotlib widget

Jupyter Notebook %matplotlib inline Not Working

I'm trying to use Jupyter notebook for the first time and following tutorials, but I'm having trouble getting plots to actually draw. I'm using the %matplotlib inline command, and its not giving me an error, but it's not drawing any plots either.
My notebook is:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
In [2]:
df = pd.read_csv('election results.csv', index_col='ons_id')
In [3]:
df['valid_votes-2015'].plot
Out[3]:
<pandas.tools.plotting.SeriesPlotMethods object at 0x000002B03AFEF6A0>
Any help would be appreciated.
Thanks
You need to call plot():
df['valid_votes-2015'].plot()
You just get the method object plot with:
df['valid_votes-2015'].plot
but you need to make it do something with the added parenthesis.

How can I change the tools on a bokeh plot created using mpl.to_bokeh?

I am trying to display a complex signal in x and y and have the awesome interactive tools available from bokeh inside of an ipython notebook. In particular I would like to restrict the wheel zoom to the x axis, but I can't see how to do this after using mpl.to_bokeh(). Is there a way to set the default tools before using mpl.to_bokeh()?
For context here is a sample plot I would like to use:
import matplotlib.pyplot as plt
import bokeh.plotting as blt
from bokeh import mpl
from bokeh.plotting import show
blt.output_notebook()
import numpy as np
blt.figure(tools='xwheel_zoom') # this doesn't help
x= np.arange(100)/100
y= np.exp(1j*2*np.pi*x)
ax= plt.subplot(211)
plt.plot(x,y.real)
plt.subplot(212, sharex=ax)
plt.plot(x,y.imag)
fig= mpl.to_bokeh(name='subplots')
Unfortunately, doing this with the MPL compat layer would already be somewhat difficult with just a single plot. I am not sure there is currently any way at all to do it with a grid plot and MPL. However, it is pretty trivial to do if you use the bokeh API directly. In case that is an option for you, and it is helpful:
from bokeh.plotting import figure, gridplot, show
import numpy as np
x = np.arange(100)/100
y = np.exp(1j*2*np.pi*x)
p1 = figure(tools='xwheel_zoom')
p1.line(x,y.real)
p2 = figure(tools='xwheel_zoom')
p2.line(x,y.imag)
grid = gridplot([[p1, p2]])
show(grid)

Categories