微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何更新 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 举报,一经查实,本站将立刻删除。