Jupyter中的互动动画图

时间:2019-12-19 09:29:13

标签: python pandas matplotlib jupyter seaborn

我有一个df,其中包含一些与ipywidgets交互过滤的数据。这是过滤df的代码:

@interact_manual(channel=channel_widget,currency=currency_widget,
                 use_cumulative=cumulative_widget)
def filter_df_1(channel, currency, use_cumulative):
    filtered1 = df[(df['SALES CHANNEL'].isin(channel)) & 
                         (df['CURRENCY']==currency)]
    return filtered1

此代码可以正常工作并产生预期的输出。

过滤数据后,我希望在同一图上绘制两条KDE线(我使用的是Seaborn,但只要我能使动画正常工作,我就不介意任何图库),然后为该图设置动画逐月,在同一图形上每个月绘制两条线,并擦除上个月的线。这是无效的代码:

def animate_kde():
    fig = plt.figure()
    plt.xlim(0,17500)
    plt.xlabel('Price')
    plt.ylabel('Density')
    month_list = ['','January','February','March','April','May','June','July',
                  'August','September','October','Novemer','December']
    plt.title('Price Density {}'.format(month_list[current_date]))

    data = filter_df_1(channel_widget.value,currency_widget.value,cumulative_widget.value)
    data = data[data['MONTH']==current_date]
    base = data.groupby('FAMILY')[' PRICE/UNIT (EGP) '].mean().rename('BASE')
    ax1 = sns.kdeplot(base)
    ax2 = sns.kdeplot(data[' PRICE/UNIT (EGP) '])

    def init():
        plt.cla()
        ax1 = sns.kdeplot(base)
        ax2 = sns.kdeplot(data[' PRICE/UNIT (EGP) '])

    def animate(i):
        plt.cla()
        current_date=i
        ax1 = sns.kdeplot(base)
        ax2 = sns.kdeplot(data[' PRICE/UNIT (EGP) '])

    anim = animation.FuncAnimation(fig, animate, init_func=init, 
                                   frames=range(0,12), interval=1000)

    rc('animation',html='jshtml')

    HTML(anim.to_jshtml())


animate_kde()

运行时,此代码只会生成一个静态图像,该图像不会进行动画处理,也不会通过与小部件进行交互来观察df过滤的变化。

像这样:

Plot

我没有接受过程序员的培训,所以我知道我可能在代码中犯了很多错误。

所需的输出是一个动画图,它通过交互式小部件观察df的过滤。

0 个答案:

没有答案