【问题标题】:clear output of output widget plotting a Seaborn figure does not work绘制 Seaborn 图形的输出小部件的清除输出不起作用
【发布时间】:2021-04-03 12:32:45
【问题描述】:

我想创建一个带有多个下拉框的输出小部件和一个带有 Seaborn 的绘图,如下所示。 目的是使用不同的下拉框来选择变量,并根据用户输入输出不同的 Seaborn 图。

这里是代码。它有效,但不如预期。

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)

上述代码不会在每次选择一个新的保管箱变量时清除输出小部件,并添加 Seaborn 图。

我看到了这些解决方案: Stop seaborn plotting multiple figures on top of one another

根据我的意见,这并不令人满意。我想每次在输出小部件中显示一个新图形,即完全清除内容然后再次添加内容;再次阴谋。 我不明白为什么 clear_output() 清除文本行而不清除图形。

其次,正如上述链接中的一些答案所指出的,如果与 Seaborn 合作,我不想求助于底层库,即 Matplotlib。我认为这是一种解决方法。

那么正确的方法是什么?

谢谢

【问题讨论】:

    标签: python seaborn ipywidgets


    【解决方案1】:

    以下代码对我有用。

    我不确定这是否是一个错字,但你写的是 clear_output() 而不是 myout.clear_output()

    另外,我相信您需要在回调结束时致电plt.show()

    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)
    

    【讨论】:

    • 这就是诀窍。在我的代码中这一行 plt.title("Correlation matrix");以 ';​​' 结尾删除那个“;”并添加您的 plt.show() 行将使其正常工作。问题仍然存在为什么?
    猜你喜欢
    • 2022-01-04
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多