简体   繁体   English

如何自定义情节图例顺序?

[英]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?我想将箱线图中图例的顺序从 1 更改为 12,或者甚至将它们重命名为 Jan、Feb 等。知道我该怎么做吗?

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: px.box按照它读取 DataFrame df的顺序绘制数据,因此您可以将排序的 DataFrame 传递给 px.box:

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',... :如果您想要月份的名称,您可以通过将'month'列映射到其各自的缩写(例如'Jan', 'Feb',...来在 DataFrame 中创建一个新列:

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:然后将'month_name'而不是'month'传递给您的make_box_plot函数应该创建一个以 month_name 作为图例条目的图表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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