Black Lives Matter. Please consider donating to Black Girls Code today.

How to sort plotly bar chart using category from another column ()

Hi all,

I am trying to plot a my bar chart such that “name” is my X Axis but i want sort them based on “category 1” and also to color the bars according to that category.

Category 1 Name Volume
A eee 20
A rrr 40
A ttt 30
B yyy 50
B fff 10
B ddd 20
C ccc 30
C www 10
C bbb 70
D hhh 80
D jjj 5
D ttt 60

ideally this is what i hope to acheive from my bar chart. Any idea how can i do that?


thank you!

Using Plotly Express, you could pass the category column name to the color parameter. All bars with the same category should then be colored accordingly.

The closest I could replicate is with the following code:

# %%
import pandas as pd
import as px
import plotly.graph_objects as go

# %%
df = pd.DataFrame({
    "category": ['A', 'A', 'B', 'B', 'C'],
    "name": ['aa', 'a2', 'be', 'bk', 'cp'],
    "volume": [10, 20, 2, 8, 13],

fig =, x='name', y='volume', color='category')

which generates:

Hi Pokgak,

thanks for the above, it certainly help but i think i found a second issue. i think i will need to have a 2 level category for my x-axis. The above looks good but i also realised that some of my “names” are repeating in different category and in those cases the bars are stacked, instead i had like them to still be separated by “category 1”


import pandas as pd
import as px
import plotly.graph_objects as go


dff = pd.DataFrame({
“category”: [‘A’, ‘A’, ‘B’, ‘B’, ‘C’,‘C’],
“name”: [‘aa’, ‘a2’, ‘de’, ‘bk’, ‘cp’,‘de’],
“volume”: [10, 20, 2, 8, 13,6],

fig =, x=‘name’, y=‘volume’, color=‘category’, width=400, height=300)


any idea how can i create the dual level x axis in the example previously?

thank you!!