Skip to content
Advertisement

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. 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.

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.

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
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()]}
)

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement