im using plotly.express.
temp_dataframe = pd.DataFrame()
temp_dataframe['VALUE'] = relevant_dataframe.RESULT.tolist()
temp_dataframe['SITE_NUM'] = relevant_dataframe.SITE_NUM.tolist()
temp_dataframe.sort_values('VALUE', inplace = True)
temp_dataframe['IDX'] = list(range(len(temp_dataframe)))
fig=px.line(temp_dataframe, x = 'VALUE', y = 'IDX', color='SITE_NUM')
fig.update_layout(
yaxis = dict(
tickmode = 'array',
tickvals = (len(d)-1) * p/100,
ticktext = p
)
)
fig.show()
my plot requires the ‘VALUES’ column to be sorted and plotted according to it, which then results in another column ‘SITE_NUM’ to be arranged seemingly randomly. but i need the legend to be in increasing order based on ‘SITE_NUM’ column, while not changing the shape of the graph
most google searches and stackoverflow replies seem to imply that i have to sort the ‘SITE_NUM’, but this screws up the main shape of the plot. is there a way to simply reorder the final legend after plotting?
Some data: (first column is not labelled)
VALUE SITE_NUM IDX
1171 321874.031250 0 1355
486 239604.937500 0 256
169 275894.156250 1 1230
1188 252101.953125 1 565
446 230880.828125 2 114
827 271964.843750 2 1145
745 272814.093750 3 1167
358 272098.781250 3 1149
419 275497.187500 4 1223
932 275310.375000 4 1217
>Solution :
By default, Plotly Express lays out legend items in the order in which values appear in the underlying data. Every Plotly Express function also includes a category_orders keyword argument which can be used to control the order in which categorical axes are drawn, but beyond that can also control the order in which legend items appear, and the order in which facets are laid out.
So you can try,
fig=px.line(temp_dataframe, x='VALUE', y='IDX', color='SITE_NUM', category_orders={"SITE_NUM": ['0', '1', '2', '3', '4']})
where category_orders you like.
If you want to reversed it:
fig.update_layout(legend_traceorder="reversed")
More details can be found here