Search code examples
pandasvisualizationplotly-pythonplotly-express

Get a separate bar for each row in Plotly when data has duplicate categories


I have a very simple dataframe with some duplicated category values:

import pandas as pd
df = pd.DataFrame({'x': ['Alpha', 'Beta','Beta','Beta','Gamma','Delta','Delta'], 'y': [12,11,9,7,5,3,1]})
x y
0 Alpha 12
1 Beta 11
2 Beta 9
3 Beta 7
4 Gamma 5
5 Delta 3
6 Delta 1

and I would like to use Plotly (Python) to produce a bar chart like I would get in Excel where each row has its own, separate bar like this:

screenshot of example bar chart in excel

Plotly produces something like this where the Beta and Delta values are sort of stacked on to each other:

import plotly.express as px
px.bar(df, x='x', y='y')

screenshot of same bar chart in plotly

This feels like it should be easy to do but reading the Plotly docs / Google / SO searches so far have not produced a result (possibly because I struggled to work out the best search terms) but how to achieve this?

I have tried setting type='category' and barmode='group' and categoryorder='total descending' in various combinations, none of which have forced an individual, separate bar per row like in Excel that I want.


Solution

  • Definitely not intuitive and had to dig beyond the px.bar docs for sure.

    import plotly.express as px
    import pandas as pd
    
    
    df = pd.DataFrame({'x': ['Alpha', 'Beta','Beta','Beta','Gamma','Delta','Delta'], 'y': [12,11,9,7,5,3,1]})
    
    fig = px.bar(df, x=df.index, y='y')
    fig.update_layout(
        xaxis = dict(
            tickmode = 'array',
            tickvals = df.index,
            ticktext = df.x
        )
    )
    fig.show()
    

    gives

    enter image description here