如何更新 matplotlib 小部件而不是重新绘制图形

问题描述

我正在尝试将生物数据绘制到一个小部件中,用户应该能够在其中选择给定数据的时间跨度和所需类型(以下示例中的水果类型)。我想出了如何将它们连接在一起,但我似乎不明白如何更新情节而不是每次都重新绘制一个新的情节。我通过关闭预先存在的图形来修补它,但这听起来不正确。我找到了一些基于 OO 解决方案的答案,但我在解释它们时遇到了问题...

导入和虚拟数据

from IPython.display import display
import ipywidgets as widgets
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
# plotting theme
sns.set_theme(context="paper",style="darkgrid")
%matplotlib widget

#generate data
dti = pd.date_range("2018-01-01",periods=1000,freq="D")
d = {"A":["Apple","Banana"] * 500,"B":np.random.randint(0,1000,size=(1000))}
df = pd.DataFrame(d,index = dti)
df

小工具

labels = df["A"].unique()

### creating date picker system
start_date_picker = widgets.DatePicker(
    description='Starting date',value=df.index[0],disabled=False
)
end_date_picker = widgets.DatePicker(
    description='Starting date',value=df.index[-1],disabled=False
)
# An HBox lays out its children horizontally
ui = widgets.HBox([start_date_picker,end_date_picker])

### creating line picker system
feat_pick1 = widgets.CheckBox(value=True,description= labels[0])
feat_pick2 = widgets.CheckBox(value=True,description= labels[1])
# An HBox lays out its children horizontally
ui_on = widgets.HBox([feat_pick1,feat_pick2])


### plotting
def plot(start,end,on1,on2):
    
    # I didn't figure out how to update the plot instead of drawing a new one,# so I fixed it by closing the old one
    plt.close()
    
    # prepare data based on date selection
    df_plot = df[start:end]

    # plot new line for each label in the given dataset
    fig,ax = plt.subplots( figsize=(9,6))
    for i in range(0,len(labels)):
        sns.scatterplot(x = df_plot.loc[df_plot["A"] == labels[i],"B"].index,y = df_plot.loc[df_plot["A"] == labels[i],"B"],label=labels[i]
                       )
    
    # line selection,accessing the artist of each line to hide them
    ax.collections[0].set(visible=on1)
    ax.collections[1].set(visible=on2)
    
    # update legend with picked options
    plt.legend()
    
    
# draw the whole widget
out = widgets.interactive_output(plot,{'start': start_date_picker,'end': end_date_picker,'on1':feat_pick1,'on2':feat_pick2}
                                )

display(out,ui,ui_on)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)