0

I want to plot plotly express grouped bar chart to show no of births in each decade just like this graph.

pivot_dayofweek=final.pivot_table(values='births',index='dayofweek',columns='decade',aggfunc='mean')    



pivot_dayofweek=pivot_dayofweek.loc[['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']]
pivot_dayofweek

pivot_dayofweek dataframe

px.bar(pivot_dayofweek,x=pivot_dayofweek.index,y=pivot_dayofweek.values,barmode='group')

but when I run the above code it gives me an error Click to show the error

1 Answers1

0
  • have simulated data set and pivot table
  • simplest way is to restructure pivot dataframe to be ready for plotly
    1. stack() decade columns into index
    2. reset_index() to make index columns
    3. make decade a string to prevent it being treated as continuous
import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({"date": pd.date_range("1-jan-1960", "31-dec-1989", freq="D")}).pipe(
    lambda d: d.assign(
        births=np.random.uniform(1, 5, len(d)),
        dayofweek=d["date"].dt.strftime("%A"),
        decade=d["date"].dt.year - d["date"].dt.year % 10,
    )
)

dfp = df.pivot_table(
    values="births", index="dayofweek", columns="decade", aggfunc="sum"
)

px.bar(
    dfp.stack().reset_index().assign(decade=lambda d: d["decade"].astype(str)),
    color="decade",
    x="dayofweek",
    y=0,
    barmode="group",
).update_layout(title="No of birth in day in every decade", yaxis={"title":"Births"})

enter image description here

Rob Raymond
  • 29,118
  • 3
  • 14
  • 30