Search code examples
pythonplotlylegendboxplotplotly-express

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()

My Data frame. Note the month column

Result of my plot


Solution

  • 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)