繁体   English   中英

如何使用 Plotly Python 对事件的直方图进行动画处理?

[英]How can I animate a histogram of occurrences using Plotly Python?

我想在DataFrame索引上制作一个直方图动画,这样随着索引的增加,箱子就会填满。 我的DataFrame的结构如下:

指数 成分
1 洋葱
2 洋葱
3
4 洋葱
5 番茄
6 番茄
7 洋葱

在 animation 的开头,所有的 bin 都应该初始化为 0,并随着索引的增加而填满。 我使用plotly.express.histogram尝试了以下操作。

idx = df.index
fig = px.histogram(df, x="Ingredient",
    animation_frame=idx, animation_group=idx, cumulative=True,
)

我得到的结果是一个动画直方图,其中只有一个 bin在通过DataFrame时在成分名称之间切换,并且 bin 的高度保持恒定为 1。

  • 方法是准备一个 dataframe 准备好用于 animation
  • 然后很容易创建一个动画来创建您定义的图形
import pandas as pd
import plotly.express as px
import io

df = pd.read_csv(
    io.StringIO(
        """Index,Ingredient
1,Onions
2,Onions
3,Garlic
4,Onions
5,Tomato
6,Tomato
7,Onions"""
    )
)


ings = df["Ingredient"].value_counts()
df2 = pd.concat(
    [
        pd.DataFrame({"Ingredient": ings.index})
        .merge(
            df.loc[df["Index"].le(i)].groupby("Ingredient", as_index=False).size(),
            on="Ingredient",
            how="left",
        )
        .assign(Index=i)
        .fillna(0)
        for i in range(df["Index"].min(), df["Index"].max() + 1)
    ]
)

px.bar(df2, x="Ingredient", y="size", animation_frame="Index").update_layout(
    yaxis={"range": [0, ings.max()]}
)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM