Removing tool bar and figure title when using jupyter-matplotlib - python

I'm using jupyter-matplotlib to embed charts as widgets in a jupyter widgets based dashboard. However, I would like to disable the interactive tool bar and the figure title that automatically gets added.
As a simple example, the below creates an empty figure but it still has the interactive tool bar and Figure title.
%matplotlib widget
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
I would like to remove both the tool bar and figure title as well as anything else that is added padding around the plot, which I may not be able to see.

If you are using the latest jupyter-matplotlib version (0.5.3 as I am writting), you can use:
fig.canvas.toolbar_visible = False
fig.canvas.header_visible = False
fig.canvas.footer_visible = False
You can also disable the resizing:
fig.canvas.resizable = False

To get rid of toolbar you can use this
mpl.rcParams['toolbar'] = 'None'
To remove title you can set the title to me empty something like this
fig.set_title("")
Hope this helps!

Related

Jupyter Notebook: duplicated scatter plot using when using ipywidgets

I'm trying to control the display of a scatter plot with a checkbox. When I built it using the interact function it worked as expected. The plot was shown or hidden based on the value in the checkbox.
import matplotlib.pyplot as plt
from ipywidgets import interact, widgets
%matplotlib inline
def on_change(Display):
if Display == True:
plt.scatter(x,y)
plt.show()
return Display
interact(on_change, Display=False);
When I tried to do the same thing using the observe function every time I clicked on the checkbox I get an additional plot displayed below. What do I need to do to get it to redraw the same plot so it works like the example above?
I suppose something in the interact example is clearing the display but it's not clear how to do this manually.
import matplotlib.pyplot as plt
from ipywidgets import interact, widgets
%matplotlib inline
x = [1,2,3,4,5,6,7,8]
y = [5,2,4,2,1,4,5,2]
def on_change(change):
if change['new'] == True:
scat = plt.scatter(x,y)
plt.show()
cb = widgets.Checkbox(False, description = "Display")
cb.observe(on_change, names='value')
display(cb)
A couple of alterations I made to your example to hopefully demonstrate what you want. I have taken a more object-oriented route, not sure if you specifically wanted to avoid it but it helps achieve your desired outcome, it seems like you are moving towards a simple GUI here.
1) Include an Output widget (out) - basically a cell output which you can display like a normal widget. You can use a context manager block (with out:) when you want to print to that specific output widget. You can also clear the widget with out.clear_output()
2) Use the object oriented interface in matplotlib rather than using plt. I find this easier to control which plots are displayed and in which location at the right times.
temporarily suspend the interactive matplotlib with plt.ioff()
Create your figure and axis with fig, ax = plt.subplots(). NB figures can have multiple axes/subplots but we only need one.
'plot' the scatter data to your axis using ax.scatter(x,y), but this won't cause it to appear.
Explicitly display the figure with display(fig).
I'm assuming you want your figure to be replotted each time you check the box, so I have included it in the observe function. If your figure doesn't change, it would make sense to move it outside of the loop.
import matplotlib.pyplot as plt
from ipywidgets import interact, widgets
%matplotlib inline
out = widgets.Output()
x = [1,2,3,4,5,6,7,8]
y = [5,2,4,2,1,4,5,2]
def on_change(change):
if change['new'] == True:
with out:
plt.ioff()
fig,ax = plt.subplots()
ax.scatter(x,y)
display(fig)
else:
out.clear_output()
cb = widgets.Checkbox(False, description = "Display")
cb.observe(on_change, names='value')
display(cb)
display(out)

How can I display and update two matplotlib plots in the same window at the same time?

I've implemented a GUI that displays two dropdown menus in which you can choose two different set of graphs to be displayed. However when I create the graphs with the following code:
import matplotlib.pyplot as plt
from matplotlib.backends.backedn_qt4agg import FigureCanvasQTAgg as FigureCanvas
self.comparison_figure1 = plt.figure(figsize=(15,5))
self.comparison_canvas1 = FigureCanvas(self.comparison_figure1)
self.comparison_figure2 = plt.figure(figsize=15,5))
self.comparison_canvas2 = FigureCanvas(self.comparison_figure2)
And then I try to update the plots (plt.tight_layout() for example)
def on_resize(event):
plt.tight_layout()
self.comparison_canvas2.draw()
self.comparison_canvas1.draw() #this would do nothing
cid = self.comparison_canvas2.mpl_connect('resize_event', on_resize)
only the last plot called with "plt." is updated. How do I write my code so that I can reference both plots.
I've also tried to create one plot where I have both graphs being displayed side by side but because of the need to update the graphs independently I encountered more problems. If you are able to make it work that way instead, great! I'm just thinking that fixing the previous problem may be simpler.
If you need more code I can post it!
#
#
Solution (Thanks to ImportanceOfBeingErnest and Ash Sharma):
replace any "plt." with the specific figure
for example:
plt.tight_layout() #replace with self.comparison_figure1.tight_layout()
So this is some of the fixed code:
def on_resize(event):
self.comparison_figure1.tight_layout()
self.comparison_figure2.tight_layout()
self.comparison_canvas1.draw()
self.comparison_canvas2.draw()
cid = self.comparison_canvas2.mpl_connect('resize_event', on_resize)
#
#
Problem:
Previous solution hasn't fixed all plot updating issues. Though "plt" can be replaced with self.comparison_figure1 when using tight_layout(), the same cannot be done when using cla() to clear the plot.
Code where I'm using cla():
sns.set(style="whitegrid")
plt.cla()
ax = self.comparison_figure2.add_subplot(111)
.....
.....
I can post more code if you need it!
Solution (Thanks to ImportanceOfBeingErnest and Ash Sharma):
replace any plt with the specific figure
for example:
plt.tight_layout() #replace with self.comparison_figure1.tight_layout()
So this is some of the fixed code:
def on_resize(event):
self.comparison_figure1.tight_layout()
self.comparison_figure2.tight_layout()
self.comparison_canvas1.draw()
self.comparison_canvas2.draw()
cid = self.comparison_canvas2.mpl_connect('resize_event', on_resize)

Python Matplotlib: Clear figure when figure window is not open

I'm working with matplotlib plotting and use ioff() to switch interactive mode off to suppress the automatic opening of the plotting window on figrue creation. I want to have full control over the figure and only see it when explicitely using the show() command.
Now apparently the built-in commands to clear figures and axes do not work properly anymore.
Example:
import numpy as np
import matplotlib.pyplot as mpp
class PlotTest:
def __init__(self,nx=1,ny=1):
# Switch off interactive mode:
mpp.ioff()
# Create Figure and Axes:
self.createFigure(nx, ny)
def createFigure(self,nx=1,ny=1):
self.fig, self.axes = mpp.subplots(nx,ny)
if nx*ny == 1:
self.axes = np.array([self.axes])
def linePlot(self):
X = np.linspace(0,20,21)
Y = np.random.rand(21)
self.axes[0].plot(X,Y)
P = PlotTest()
P.linePlot()
P.fig.show()
Now I was thinking I could use P.fig.clear() any time to simply clear P.fig, but apparently that's not the case.
Writing P.fig.clear() directly into the script and execute it together it works and all I see is an empty figure. However that's rather pointless as I never get to see the actual plot like that.
Doing P.fig.clear() manually in the console does not do anything, regardless if the plot window is open or not, all other possible commands fail as well:
P.fig.clf()
P.axes[0].clear()
P.axes[0].cla()
mpp.clf()
mpp.cla()
mpp.close(P.fig)
Wrapping the command into a class method doesn't work either:
def clearFig(self):
self.fig.clear()
EDIT ================
After a clear() fig.axes is empty, yet show() still shows the old plot with the axes still being plotted.
/EDIT ================
Is it because I switched off interactive mode?
If you add a call to plt.draw() after P.fig.clear() it clears the figure. From the docs,
This is used in interactive mode to update a figure that has been altered, but not automatically re-drawn. This should be only rarely needed, but there may be ways to modify the state of a figure with out marking it as stale. Please report these cases as bugs.
I guess this is not a bug as you have switched off interactive mode so it is now your responsibility to explicitly redraw when you want to.
You can also use P.fig.canvas.draw_idle() which could be wrapper in the class as clearFigure method.

Matplotlib figures not changing interactively - Canopy Ipython

I am trying to use the ipython in canopy with matplotlib to prepare graphs (backend set to qt). I wrote the following code line by line int the terminal
import matplotlib.pyplot as plt
fig = plt.figure()
s = fig.add_subplot(1,1,1)
after the second line I can see the figure being made. However after the third line I do not see the sub plot being created. However If I print fig, the sub-plot is can be seen both inline and in the figure window created. This sub-plot also magically appears if I try to zoom. Similar thing happens every time i plot something on the figure. The old version is displayed till I either print the figure or if i try to modify the view using the GUI tools. This is really annoying. It would be great if someone could tell me where the problem is.
Edit: Tried using fig.show() which does not work. Also when I use the plt.plot() directly, there seems to be no problem. The problem comes only when i use fig or any of its subplots
type:
fig.show() when you need to update it.
you should try using fig.canvas.draw() instead of using fig.show() when it comes to interactive plots.
import matplotlib.pyplot as plt
fig = plt.figure()
fig.show()
## should show an empty figure ##
s = fig.add_subplot(1,1,1)
fig.show()
## things stay unchanged ##
fig.canvas.draw()
## things should be OK now ##

Python and Interactive Zoom Plot with Matplotlib

I am using a Matplotlib plot (with Basemap) inside of a wxPython pane. I have got the plot (US map with scatter plot of cities). I am trying to do some interactive zoom capabilities (select a box on the map and "zoom" into that area only).
I have managed to get the toolbar to show, but when i click on the buttons, nothing happens. Seems like the toolbar is just there for show. Any Thoughts? Here is my code:
# Set up area for plotting Basemap Plot and scatter plot
self.figure = Figure(None,dpi=75)
self.canvas = FigureCanvas(self.PlotPanel, -1, self.figure)
self.axes = self.figure.add_axes([0,0,1,1],frameon=False)
self.SetColor( (255,255,255) )
# Toolbar Set up
self.toolbar=NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
tw,th = self.toolbar.GetSizeTuple()
fw,fh = self.canvas.GetSizeTuple()
self.toolbar.SetSize(wx.Size(fw,th))
sizer_7.Add(self.toolbar,0)
self.toolbar.update()
Have a look at the embedding_in_wx2 example, which works fine for me.
Maybe there is something wrong with your imports: you first have to import matplotlib, than set the backend (matplotlib.use('WXagg')) and then import the backend.
However it isn't easy to help you without having a full example with all imports.

Categories