Plotly Ignoring "barmode=group" Argument in Bar Chart

Question:

I am trying to create a grouped barchart with this data on plotly, but that argument gets ignored each time and plotly creates a relative barchart instead. I tried changing the column, index, and value datatypes to no avail.

My code is below:

data='''
Brand   2018    2019    2020    2021
Hersheys    100 200 212 314
MilkyWay    105 106 214 178
Reeses  84  82  95  112
Payday  278 552 214 292
'''

brand = pd.read_csv(StringIO(data), sep='s+')
brand=pd.melt(brand,id_vars=['Brand'],value_vars=brand.columns)
brand=brand.rename(columns={'variable':'Year'})

agg_brand=brand[['value','Year']].groupby('Year').agg('sum').reset_index()
agg_brand.columns=['Year','value_sum']
brand=pd.merge(brand,agg_brand,on='Year',how='left')

brand['percent']=(brand['value']/brand['value_sum']*100).round(1).astype(str)+"%"
fig=px.bar(brand,x='Year',y='value',barmode='group')
fig.show()

I found this link, but I have no clue how to apply it. I am lost (and I also have to make these charts by tomorrow) and any help is appreciated. Thanks

Stacked Rather Than Grouped Barchart

Asked By: dlnvss

||

Answers:

You need to specify the color argument as well, and then you’ll get the side-by-side bars.

fig=px.bar(brand,x='Year',y='value', barmode='group', color='Brand')
fig.show()

enter image description here

I tried this with your dataframe at various points in the creation and I might have done something wrong, but there’s nothing to indicate that it should need color specified, even from reading the plotly code.

Answered By: wkl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.