0

I want to create a output widget with several drop boxes and a plot with Seaborn as follows. The intention is having different drop boxes to choose variables and according to user input output a different Seaborn plot.

Here the code. It works but not as desired.

dd = wd.Dropdown(
    options=["YlGnBu","Blues","BuPu","Greens"],
    value="Blues",
    description='chosse cmap:',
    disabled=False,
)

myout = wd.Output()

def draw_plot(change):
    with myout:
        myout.clear_output()
        print('plotting out the following:   sns.heatmap(df.corr(), annot=True, cmap = "YlGnBu")')
        plt.figure(figsize=(8, 3))
        sns.heatmap(df.corr(), annot=True, cmap = change.new)
        plt.title("Correlation matrix");

dd.observe(draw_plot, names='value')
display(dd)
display(myout)

The above code DOES NOT CLEAR THE OUTPUT WIDGET every time a new variable of dropbox is selected, and Seaborn plots are added.

I saw these solutions: Stop seaborn plotting multiple figures on top of one another

that are not satisfactory according to my opinion. I would like to display in the output widget a new figure every time, i.e. totally clear the content and then add stuff again; plot again. I don't understand why clear_output() clears the text line but not the figure.

secondly, as some answers in the mentioned linked pointed out if working with Seaborn I don't want to resort to an underlying library, i.e. Matplotlib. I considere that a work around.

So how is the proper way to go?

thanks

JFerro
  • 3,203
  • 7
  • 35
  • 88

1 Answers1

1

The following code works for me.

I'm not sure if that was a typo, but you wrote clear_output() instead of myout.clear_output()

also, I believe you need to call plt.show() at the end of your callback.

import ipywidgets as wd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

a = np.random.random(size=(5,5))

dd = wd.Dropdown(
    options=["YlGnBu","Blues","BuPu","Greens"],
    value="Blues",
    description='chosse cmap:',
    disabled=False,
)

myout = wd.Output()

def draw_plot(change):
    with myout:
        print('plotting out the following:   sns.heatmap(df.corr(), annot=True, cmap = "{}")'.format(change.new))
        myout.clear_output()
        sns.heatmap(a, annot=True, cmap = change.new)
        plt.show()

dd.observe(draw_plot, names='value')
display(dd)
display(myout)
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • here is the trick. in my code this line plt.title("Correlation matrix"); ends up with ';' removing that ";" and adding your line plt.show() will make it work properly. the question still remains WHY? – JFerro Dec 25 '20 at 22:50