Jupyter, Interactive Matplotlib: Hide the toolbar of the interactive view - python

I am starting using the interactive plotting from Matplotlib:
%matplotlib notebook
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, figsize=(8, 3))
plt.plot([i for i in range (10)],np.random.randint(10, size=10))
plt.show()
Anyone knows if there is a way to hide the toolbars of the interactive mode?

I disabled the interactive mode buttons and toolbar with some python generated css.
Run the following in one of the notebook cells:
%%html
<style>
.output_wrapper button.btn.btn-default,
.output_wrapper .ui-dialog-titlebar {
display: none;
}
</style>
Unfortunately there's no good css selectors on the buttons, so I've tried to use as specific selector as possible, though this may end up disabling other buttons that you might generate in the output cell.
Indeed, this approach affects all output cells in the notebook.

Use the magic %matplotlib ipympl with canvas. toolbar_visible=False. To prevent double-appearence of figure, use plt. ioff() while instantiate figure:
import matplotlib.pyplot as plt
plt.ioff()
fig, ax = plt.subplots()
plt.ion()
fig.canvas.toolbar_visible = False
display(fig.canvas)
It's a little bit doubly, but so you know how to play with plt
Edit: Haven't mind you on jupyter. This works on jupyterlab

Related

refresh matplotlib in Jupyter when updating with ipywidget

I want to draw a line in a Jupyter notebook, which can be moved using an ipywidget slider. I also want to have the mouse coordinates displayed, for which I'm using %matplotlib notebook. Here is what I have so far :
%matplotlib notebook
from ipywidgets import interact
fig, ax = plt.subplots()
#interact(n=(-200, 0))
def show(n):
# fig.clear() #doesn't show anything
y = -n+x
ax.plot(x, y)
plt.show()
When moving the line using the slider, the plot doesn't refresh, all previous positions of the line
remain visible:
I tried to refresh using fig.clear(), but then noting shows.
How can I solve this?
I have an extensive answer about this here: Matplotlib figure is not updating with ipywidgets slider
but the short of my recommendations are:
use ipympl %matplotlib ipympl instead of notebook as this will play nicer with ipywidgets
Use mpl-interactions to handle making plots controlled by sliders.
It will do the optimal thing of using set_data for you rather than clearing and replotting the lines.
It also interprets the shorthand for numbers in a way that (I think) makes more sense when making plots (e.g. using linspace instead of arange) see https://mpl-interactions.readthedocs.io/en/stable/comparison.html for more details.
So for your example I recommend doing:
install libraries
pip install ipympl mpl-interactions
%matplotlib ipympl
from ipywidgets import interact
import matplotlib.pyplot as plt
from mpl_interactions import ipyplot as iplt
x = np.linspace(0,100)
fig, ax = plt.subplots()
def y(x, n):
return x - n
ctrls = iplt.plot(x, y, n=(-200,0))
it got a bit longer because I added the imports you left out of your question and also defined x.
Which gives you this:
That said if you don't want to use those I think what you want is ax.cla() I think when you do fig.clear you are also removing the axes which is why nothing shows up.
%matplotlib notebook
from ipywidgets import interact
fig, ax = plt.subplots()
#interact(n=(-200, 0))
def show(n):
y = -n+x
ax.cla()
ax.plot(x, y)
plt.show()

Mix matplotlib interactive and inline plots?

Many plots just doesn't need to be interactive so I tried to change them to inline plots.
I tried the following without success:
plt.close(fig). It clear the figure
plt.ioff(), failed
wrap codes between %matplotlib inline %matplotlib notebook. It close other interactive plots
There can only ever be one single backend be active. It would be possible to change the backend, but that would require to close the interactive figures.
An option is to work with interactive backend throughout (e.g. %matplotlib widget) and call a custom function that shows a png image inline once that is desired.
#Cell1
%matplotlib widget
#Cell2
import matplotlib.pyplot as plt
def fig2inline(fig):
from IPython.display import display, Image
from io import BytesIO
plt.close(fig)
buff = BytesIO()
fig.savefig(buff, format='png')
buff.seek(0)
display(Image(data=buff.getvalue()))
#Cell3: (show the interactive plot)
fig, ax = plt.subplots(figsize=(3, 1.7))
ax.plot([1,3,4]);
#Cell4: (show the inline plot)
fig2, ax2 = plt.subplots(figsize=(3, 1.7))
ax2.plot([3,1,1]);
fig2inline(fig2)

Clearing all seaborn plots each time running the code in plots tab spyder IDE

I create some plots in one run of code, the plots are in plots tab. I tried to delete it all each time i rerun it but somehow the previous plots are still there not closing, it only creates new plots without clearing the previous plots from the previous run. I already tried to use plt.close('all') but it does not work. How do i clear all plots every time i rerun the code?
Here's my code
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
avo_sales = pd.read_csv('avocados.csv')
avo_sales.rename(columns = {'4046':'small Hass sold','4225':'large Hass sold','4770':'xlarge Hass sold'},
inplace= True)
for column in avo_sales.columns[2:11]:
sns.set()
fig, ax = plt.subplots()
sns.set(style="ticks")
sns.boxplot(column, data= avo_sales) # column is chosen here
sns.despine(offset=10, trim=True)
The images in the plots pane are handled by Spyder and are not reachable from the IPython console.
A simple solution would be to press the "remove images" icon before you re-run the code:
I don't know how to even get Spyder to put plots in the plot pane, but here's a few things that might work.
Try disabling some of the pane options:
Try some magic functions:
%reset - reset everything
%matplotlib - puts all plots inline with your code in the interactive window
%clear - clears the interactive window
Use IPython directly to help (via: https://gist.github.com/stsievert/8655158355b7155b2dd8):
from IPython import get_ipython
get_ipython().magic('reset -sf')

Matplotlib Object Oriented Code to display inline in the notebook

Any ideas on how I can get this code
# -*- noplot -*-
"""
=============================
The object-oriented interface
=============================
A pure OO (look Ma, no pylab!) example using the agg backend
"""
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
from the matplotlib example gallery at this link to show me the chart in-line in my notebook?
Please Note:
I want to avoid using pyplot as I am trying to use matplotlib using their "Object Oriented" Library only
I have no issues getting pyplot based plots to render inline in my notebook using the %matplotlib inline or %matplotlib notebook magic
This confusing Object Oriented API of matplotlib isn't necessarily rendering inline.
Should I be using a different canvas?
Using fig.show() gives me the following error
AttributeError: 'FigureCanvasAgg' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().
Also, this particular canvas doesn't have a show method. So I am totally lost on how to get these darn Obj Oriented plots to render inline.
To display a figure which does not live in pyplot and has no figure manager associated with it, you can use IPython.core.display:
from IPython.core.display import display
display(fig)
Just note that there is actually no reason at all not to use pyplot to create the figure. Using pyplot, the code is much cleaner and will automatically show.
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts');

plt.show () does not open a new figure window

I am trying to show some plots using plt.show (). i get the plots shown on the IPython console, but I need to see each figure in a new window. What can I do ?
In your notebook, try
import matplotlib.pyplot as plt
%matplotlib
Called alone like this, it should give output in a separate window. There are also several options to %matplotlib depending on your system. To see all options available to you, use
%matplotlib -l
Calling
%matplotlib inline
will draw the plots in the notebook again.
You want to type %matplotlib qt into your iPython console. This changes it for the session you're in only. To change it for the future, go Tools > Preferences, select iPython Console > Graphics, then set Graphics Backend to Qt4 or Qt5. This ought to work.
Other option is using plt.figure:
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])
plt.show(block=False)
plt.figure(2) # a second figure
plt.plot([4, 5, 6]) # creates a subplot(111) by default
plt.show(block=False)
plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
plt.show(block=False)
(see: https://matplotlib.org/users/pyplot_tutorial.html)

Categories

Resources