How can I display a Matplotlib fig.canvas inside a ipywidgets.VBox in Google Colab?

223 Views Asked by At

I would like to have Matplotlib figures as part of a small GUI constructed from ipywidgets. So far, I can display a plot when I use the display() function directly on the plot Matplotlib widget. If I put the Matplotlib widget inside a ipywidgets.VBox and call the display() function on the VBox, the plot does not show up.

My code works in Jupyter lab but not in Google Colab.

I opended a Notebook on Google Colab and run the following.

!pip install ipympl
%matplotlib widget
from google.colab import output
output.enable_custom_widget_manager()
from ipywidgets import VBox
import numpy as np
import matplotlib.pyplot as plt

It is then possible to show a plot by calling the display() function on it.

plt.ioff()
fig = plt.figure()
plt.ion()
ax = fig.gca()
ax.plot(np.arange(10))
fig.canvas.draw()
display(fig.canvas)

Then I close the plt to start with a new plot.

plt.close()

Here I am not able to display the plot as a widget within a box.

plt.ioff()
fig = plt.figure()
plt.ion()
ax = fig.gca()
ax.plot(np.arange(10))
fig.canvas.draw()

vb = VBox([fig.canvas])
display(vb)

Here is a link with a minimal example:

https://colab.research.google.com/drive/1DJRIIECJ8hafLJweYeGswbDlj1gCNT_Q?usp=sharing

Any idea how I can get the matplotlib widget (plot) to appear in my ipywidgets.VBox?

0

There are 0 best solutions below