![](/img/trans.png)
[英]How do I make a horizontal histogram in Plotly express using 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。
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.