Sunday, 13 November 2022

How do I split a grouped bar chart into sub-groups?

I have this dataset-

              group             sub_group    value    date
0           Animal                  Cats       12     today
1           Animal                  Dogs       32     today
2           Animal                 Goats       38     today
3           Animal                  Fish        1     today
4            Plant                  Tree       48     today
5           Object                   Car       55     today
6           Object                Garage       61     today
7           Object            Instrument       57     today
8           Animal                  Cats       44     yesterday
9           Animal                  Dogs       12     yesterday
10          Animal                 Goats       18     yesterday
11          Animal                  Fish        9     yesterday
12           Plant                  Tree        8     yesterday
13          Object                   Car       12     yesterday
14          Object                Garage       37     yesterday
15          Object            Instrument       77     yesterday

I want to have two series in a barchart. I want to have one series for today and I want to have another series for yesterday. Within each series, I want the bars to be split up by their sub-groups. For example, there would be one bar called "Animal - today" and it would sum up to 83 and, within that bar, there would be cats, dogs, etc.

I want to make a chart that is very similar to chart shown under "Bar charts with Long Format Data" on the docs, except that I have two series.

This is what I tried-

fig = make_subplots(rows = 1, cols = 1)

fig.add_trace(go.Bar(
            y = df[df['date'] == 'today']['amount'],
            x = df[df['date'] == 'today']['group'],
            color = df[df['date'] == 'today']['sub_group']
        ),
    row = 1, col = 1
)

fig.add_trace(go.Bar(
            y = df[df['date'] == 'yesterday']['amount'],
            x = df[df['date'] == 'yesterday']['group'],
            color = df[df['date'] == 'yesterday']['sub_group']
        ),
    row = 1, col = 1
)

fig.show()
 

I added a bounty because I want to be able to add the chart as a trace in my subplot.



from How do I split a grouped bar chart into sub-groups?

No comments:

Post a Comment