Reputation:
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()
Upvotes: 1
Views: 3225
Reputation: 11
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()
Upvotes: 1
Reputation: 380
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
Upvotes: 1