[英]How can I animate a histogram of occurrences using Plotly Python?
I want to animate a histogram over a DataFrame
index, so that as the index increases, the bins fill up.我想在DataFrame
索引上制作一个直方图动画,这样随着索引的增加,箱子就会填满。 My DataFrame
is structured like this:我的DataFrame
的结构如下:
Index指数 | Ingredient成分 |
---|---|
1 1 | Onions洋葱 |
2 2 | Onions洋葱 |
3 3 | Garlic蒜 |
4 4 | Onions洋葱 |
5 5 | Tomato番茄 |
6 6 | Tomato番茄 |
7 7 | Onions洋葱 |
At the beginning of the animation, all bins should be initialized at 0, and fill up as the index increases.在 animation 的开头,所有的 bin 都应该初始化为 0,并随着索引的增加而填满。 I have tried the following using plotly.express.histogram
.我使用plotly.express.histogram
尝试了以下操作。
idx = df.index
fig = px.histogram(df, x="Ingredient",
animation_frame=idx, animation_group=idx, cumulative=True,
)
The result I get is an animated histogram with only one bin that switches between the ingredient names as it goes through the DataFrame
, with the height of the bin staying constant at 1.我得到的结果是一个动画直方图,其中只有一个 bin在通过DataFrame
时在成分名称之间切换,并且 bin 的高度保持恒定为 1。
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.