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

Python Plotly; color_discrete_sequence in combination with category_orders

df = pd.DataFrame({“hour_of_day”:[0,7,15,3,22,9,5], ‘UserAuth.result’: [‘A’, ‘A’, ‘D’, ‘D’,‘C’, ‘C’, ‘A’]})

fig = px.histogram(df, x=“hour_of_day”, color=‘UserAuth.result’,
color_discrete_sequence = [‘green’, ‘yellow’, ‘red’, ‘black’], range_x=[0,24],
category_orders={‘UserAuth.result’: [“A”, ‘B’,“C”, “D”]},
title=‘Histogram of fake data’)

fig.show()

I make a lot of plots before I know exactly what I can find in my dataset. I’d love to link the color_discrete_sequence with the category_orders. Right now, because label ‘B’ is missing, ‘C’ and ‘D’ get the wrong colour. How can I link them?

Hi @LZS we have a new documentation page about discrete colors. In particular what you’re looking for is the color_discrete_map argument described in this example https://plot.ly/python/discrete-color/#directly-mapping-colors-to-data-values.

1 Like

@Emmanuelle; Thank you so much!! This is exactly what I’m looking for! :partying_face: