3

I'm using seaborn on jupyter notebook and would like a slider to update a chart. My code is as follows:

from ipywidgets import interact, interactive, fixed, interact_manual
import numpy as np
import seaborn as sns
from IPython.display import clear_output

def f(var):
    print(var)
    clear_output(wait=True)
    sns.distplot(list(np.random.normal(1,var,1000)))

interact(f, var=10);

Problem: every time I move the slider, the graph is duplicated. How do I update the chart instead?

Alexis Eggermont
  • 7,665
  • 24
  • 60
  • 93
  • 1
    I think this has [been asked before](https://stackoverflow.com/questions/48380967/interact-and-plotting-with-ipywidgets-events-produces-many-graphs) and it will depend on your version of ipywidgets. – ImportanceOfBeingErnest May 12 '18 at 08:27

1 Answers1

6

Seaborn plots should be handled as regular matplotlib plot. So you need to use plt.show() to display it as explained in this answer for example.

Combined with %matplotlib inline magic command, this works fine for me:

%matplotlib inline
from ipywidgets import interact
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

def f(var):
    sns.distplot(np.random.normal(1, var, 1000))
    plt.show()
interact(f, var = (1,10))

Another solution would be to update the data of the plot instead of redrawing a new one, as explained here: https://stackoverflow.com/a/4098938/2699660

byouness
  • 1,746
  • 2
  • 24
  • 41