1

I'm working with Plotly to visualize wind data. Here I plotted the pie chart but I can't change the order of the legend. (I want to set 0-5 speed limit first and so on).Here are my code and output.

import pandas as pd
import plotly.express as px
    
fig = px.pie(df1,
             values='Cat',
             names='speed_kmhRange', 
             template="plotly_dark",
             color_discrete_sequence= px.colors.sequential.Plasma_r)
    
fig.show()

enter image description here

rpanai
  • 12,515
  • 2
  • 42
  • 64
  • 1
    Does this answer your question? [Plotly: How to customize legend order?](https://stackoverflow.com/questions/61546556/plotly-how-to-customize-legend-order) – vestland Jul 22 '20 at 07:55

2 Answers2

1

Plotly uses the order of the columns of the df to decide the order of the legend items. From plotly's dococumentation on traceorder

(Traceorder) determines the order at which the legend items are displayed. If "normal", the items are displayed top-to-bottom in the same order as the input data.

There seems to not be an option to choose by hand the legend items to show. It's always in relation to the input data's order.

So change the order of the columns to change the legend order. If you haven't done that yet, there are a few examples here

Karen Palacio
  • 350
  • 3
  • 10
1

Create a list with the custom order and assign that to the category_orders parameter.

import pandas as pd
import plotly.express as px
 
custom_order = ['0 - 5 km/h', '5 - 10 km/h', '10 - 15 km/h', '15 - 20 km/h', '20 - 25 km/h', '> 25 km/h']   
fig = px.pie(df1,
             values='Cat',
             names='speed_kmhRange', 
             category_orders = {'speed_kmhRange': custom_order},
             template="plotly_dark",
             color_discrete_sequence= px.colors.sequential.Plasma_r)
    
fig.show()
lmj97
  • 11
  • 1