如何使用 Plotly Python 为事件的直方图制作动画?
How can I animate a histogram of occurrences using Plotly Python?
我想在 DataFrame
索引上制作直方图动画,以便随着索引的增加,容器会填满。我的 DataFrame
结构如下:
Index
Ingredient
1
Onions
2
Onions
3
Garlic
4
Onions
5
Tomato
6
Tomato
7
Onions
在动画开始的时候,所有的bin都应该初始化为0,随着index的增加而被填满。我使用 plotly.express.histogram
.
尝试了以下操作
idx = df.index
fig = px.histogram(df, x="Ingredient",
animation_frame=idx, animation_group=idx, cumulative=True,
)
我得到的结果是一个动画直方图,其中 只有一个箱子 在成分名称通过 DataFrame
时在箱子的高度之间切换保持在 1。
- 方法是准备一个准备好动画的数据帧
- 那么创建一个动画就很简单了bar来创建你定义的图形
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()]}
)
我想在 DataFrame
索引上制作直方图动画,以便随着索引的增加,容器会填满。我的 DataFrame
结构如下:
Index | Ingredient |
---|---|
1 | Onions |
2 | Onions |
3 | Garlic |
4 | Onions |
5 | Tomato |
6 | Tomato |
7 | Onions |
在动画开始的时候,所有的bin都应该初始化为0,随着index的增加而被填满。我使用 plotly.express.histogram
.
idx = df.index
fig = px.histogram(df, x="Ingredient",
animation_frame=idx, animation_group=idx, cumulative=True,
)
我得到的结果是一个动画直方图,其中 只有一个箱子 在成分名称通过 DataFrame
时在箱子的高度之间切换保持在 1。
- 方法是准备一个准备好动画的数据帧
- 那么创建一个动画就很简单了bar来创建你定义的图形
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()]}
)