Daniel
Daniel

Reputation: 101

How can I get plotly Bar graph to group based on another column?

I have a dataframe like this:

from plotly import graph_objects as go
import pandas as pd


challenge_count_df = pd.DataFrame({'Challenge': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
                                  'Count' : [32, 22, 40, 12, 10, 60, 32, 22, 44, 90],
                                  'Value' : ["0","5","10","15","5","10","5","10","15","10"],
                                  'Category' : [1,2,3,4, 4, 2, 1, 3, 2, 2]})

and I have the following code:

colors = {
    'background': '#111111',
    'text': 'teal',
    "0":"silver",
    "10":"#FBEC5D",
    "5":"#50C878",
    "15":"#A23D60"
}


fig = go.Figure()
# create a bar graph with colors being different based on based on value but grouped by category
for t in challenge_count_df['Value'].unique():
    dfp = challenge_count_df[challenge_count_df['Value']==t]
    fig.add_traces(go.Bar(x=dfp['Challenge'],
                        y = dfp['Count'],
                        customdata=challenge_count_df['Category'],
                        name=t+" points",
                        marker_color=colors[t],
    ))

# Change the bar mode
fig.update_layout(barmode='group')
fig.show()

how can I make it that the bars would group up based on category? Everything else works. I just need to have the grouping to be based on the category column. Could someone please help direct me to the solution?

Upvotes: 0

Views: 697

Answers (1)

r-beginners
r-beginners

Reputation: 35155

Change the current extraction criteria to categories and set the x-axis setting to list the columns you want to group. The resulting x-axis will be represented as multiple indices.

fig = go.Figure()

for t in challenge_count_df['Category'].unique():
    dfp = challenge_count_df[challenge_count_df['Category']==t]
    fig.add_traces(go.Bar(x=[dfp['Category'], dfp['Challenge']],
                          y=dfp['Count'],
                          width=0.75,
                          customdata=challenge_count_df['Category'],
                          name=str(dfp['Category'].values[0]),
                         )
                  )

fig.update_layout(barmode='group')
fig.show()

enter image description here

Upvotes: 1

Related Questions