How to set the colored boxes in a specific order in plotly box plot?

Question:

I currently have a boxplot in plotly like so:
enter image description here

Below is the Code I used to generate it:

data = Audit_grouped[(Audit_grouped['type'] == t)
                      & (Audit_grouped['rank_desc'] == i)]
              

fig = px.box(data, x = "year", y = "hours", color = "results",
             color_discrete_map = {'Pass': 'green', 'Fail': 'red'},
             labels={"hours":"hours(sum)"}
             )

fig.update_layout(xaxis={'categoryorder':'category ascending'})
fig.update_traces(quartilemethod="linear")
fig.show()
fig.write_image('Audit '+ str(i) + ' (' + str(t) + ').png')

I want to have the Fail boxplot be displayed on the left side first as opposed to it being on the right side.

How would I go on to do that?

Asked By: The Dodo

||

Answers:

you can define that with the parameter category_orders when you create the box plot instead of updating the axes

in your case this will be as follow:

fig = px.box(data, x = "year", y = "hours", color = "results",
             color_discrete_map = {'Pass': 'green', 'Fail': 'red'},
             labels={"hours":"hours(sum)"},
             category_orders={"results": ["Fail", "Pass"]}) # this is new line
Answered By: Lucas M. Uriarte
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.