I want to animate a histogram over a DataFrame
index, so that as the index increases, the bins fill up. My DataFrame
is structured like this:
Index | Ingredient |
---|---|
1 | Onions |
2 | Onions |
3 | Garlic |
4 | Onions |
5 | Tomato |
6 | Tomato |
7 | Onions |
At the beginning of the animation, all bins should be initialized at 0, and fill up as the index increases. I have tried the following using plotly.express.histogram
.
JavaScript
x
5
1
idx = df.index
2
fig = px.histogram(df, x="Ingredient",
3
animation_frame=idx, animation_group=idx, cumulative=True,
4
)
5
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.
Advertisement
Answer
- approach is to prepare a dataframe that is ready for animation
- then it’s simple to create an animated bar to create figure you have defined
JavaScript
1
37
37
1
import pandas as pd
2
import plotly.express as px
3
import io
4
5
df = pd.read_csv(
6
io.StringIO(
7
"""Index,Ingredient
8
1,Onions
9
2,Onions
10
3,Garlic
11
4,Onions
12
5,Tomato
13
6,Tomato
14
7,Onions"""
15
)
16
)
17
18
19
ings = df["Ingredient"].value_counts()
20
df2 = pd.concat(
21
[
22
pd.DataFrame({"Ingredient": ings.index})
23
.merge(
24
df.loc[df["Index"].le(i)].groupby("Ingredient", as_index=False).size(),
25
on="Ingredient",
26
how="left",
27
)
28
.assign(Index=i)
29
.fillna(0)
30
for i in range(df["Index"].min(), df["Index"].max() + 1)
31
]
32
)
33
34
px.bar(df2, x="Ingredient", y="size", animation_frame="Index").update_layout(
35
yaxis={"range": [0, ings.max()]}
36
)
37