簡體   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