title: How to display matplotlib plots in a Jupyter tab widget?
body: <p>I am having trouble displaying plots inside of Jupyter tab widgets.  Consider the following snippet:</p>
  
  <pre><code>import matplotlib.pyplot as plt
  import pandas as pd
  import ipywidgets as widgets
  import numpy as np
  
  out1 = widgets.Output()
  out2 = widgets.Output()
  data1 = pd.DataFrame(np.random.normal(size = 50))
  data2 = pd.DataFrame(np.random.normal(size = 100))
  
  with out1:
      fig1, axes1 = plt.subplots()
      data1.hist(ax = axes1)
      display(fig1)
  
  with out2:
      fig2, axes2 = plt.subplots()
      data2.hist(ax = axes2)
      display(fig2)
  
  tab = widgets.Tab(children = [out1, out2])
  tab.set_title(0, 'First')
  tab.set_title(1, 'Second')
  display(tab)
  </code></pre>
  
  <p>(I am running Python 3.5.2, Jupyter 4.4.0, ipywidgets 7.2.1 on Ubuntu 16.04 inside a virtual environment.)</p>
  
  <p>If I put this code on the first row of the notebook and run it, I see a tab widget with two tabs, each one of which displays a string, but not the plot:</p>
  
  <p><a href="https://i.stack.imgur.com/HEYRb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HEYRb.png" alt="No plots"></a></p>
  
  <p>If I run it for a second time, or if I rerun it putting everything after the import of <code>matplotlib</code> in a second cell, I see a tab widget with one plot on each tab, but I get the two plots displayed a second time outside of the tabs. </p>
  
  <p><a href="https://i.stack.imgur.com/8dder.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8dder.png" alt="Too many plots"></a></p>
  
  <p>I can get rid of the additional displays by wrapping my code inside calls to <code>plt.ioff</code> and <code>plt.ion</code>, but <a href="https://stackoverflow.com/questions/50821003/matplotlib-figure-not-showing-up-in-output-widget-in-first-cell-of-jupyter-noteb?noredirect=1#comment88659632_50821003">it has been suggested to me</a> that this is a hack.  And in any case, it does not make matplotlib display the plots in the first cell.</p>
  
  <p><strong>Question</strong>: What is the proper way of displaying plots inside tabs?</p>