![](/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.