简体   繁体   中英

How to customize plotly legend order?

I want to change the ordering of legend in my boxplot from 1-12, or perhaps even renaming them to Jan, Feb, etc. Any idea how could I do it?

def make_box_plot(data, xdata, ydata, title, legend):
    fig = px.box(data, 
                 x= xdata, 
                 y= ydata,
                 color= xdata)

    fig.update_layout(
        title= title,
        xaxis_tickfont_size=14,
        xaxis=dict(
            title='Date',
        ),
        yaxis=dict(
            title='Sales',
            titlefont_size=16,
            tickfont_size=14,
        ),
        legend=dict(
            x=0.995,
            y=0.98,
            bgcolor='rgba(255, 255, 255, 0)',
            bordercolor='rgba(255, 255, 255, 0)',
            traceorder= 'grouped'
        ),
        showlegend= legend
    )

    fig.show()

我的数据框。注意月份栏

我的阴谋的结果

px.box is plotting your data in the order that it's reading through your DataFrame df , so you can pass a sorted DataFrame to px.box instead:

fig = px.box(data.sort_values(by=['month']), 
    x= xdata, 
    y= ydata,
    color= xdata)

If you want the names of the months, you can create a new column in your DataFrame by mapping the 'month' column to its respective abbreviation such as 'Jan', 'Feb',... :

import calendar
df['month_name'] = df['month'].apply(lambda x: calendar.month_abbr[x])

Then passing 'month_name' instead of 'month' to your make_box_plot function should create a chart with the month_name as legend entries:

make_box_plot(df, 'month_name', 'Sales', 'Cool Title', True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM