Plotly:如何自定义图例顺序?

Plotly: How to customize legend order?

我在 plotly 中 Python 制作了 scatter_geo plot。

import plotly.express as px
import pandas as pd

rows=[['501-600','65','122.58333','45.36667'],
      ['till 500','54','12.5','27.5'],
      ['more 1001','51','-115.53333','38.08'],
      ['601-1000','54','120.54167','21.98'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)

fig=px.scatter_geo(df,lon='longitude', lat='latitude',color='bins',
                      opacity=0.5,
                      projection="natural earth")
fig.show()

如果我只有一根数据,是否可以在图例标签中自定义顺序?

因为现在图例中的标签如下所示:

501-600
till 500
more 1001
601-1000

但我需要让它们看起来像这样:

till 500
501-600
601-1000
more 1001

如果您查看 traceorder,您会发现项目按照与 "normal" 选项的输入数据相同的顺序从上到下显示。因此,您只需更改输入数据的顺序即可获得所需内容:

如果您想指定任意顺序,可以通过在输入数据中定义顺序来实现。指定 row 顺序可能有点乏味,所以我经常转置数据框,对现在出现在列中的类别进行排序,然后将其转回其原始形式:

order  = ['till 500', '501-600', '601-1000', 'more 1001']
df_ordered = df.T[order].T

按照这个顺序,结果会和上图一样。这是更新后的代码片段:

完整代码:

import plotly.express as px
import pandas as pd

rows=[['501-600','65','122.58333','45.36667'],
      ['till 500','54','12.5','27.5'],
      ['more 1001','51','-115.53333','38.08'],
      ['601-1000','54','120.54167','21.98'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)

fig=px.scatter_geo(df,lon='longitude', lat='latitude',color='bins',
                      opacity=0.5,
                      projection="natural earth")
fig.show()


order  = ['till 500', '501-600', '601-1000', 'more 1001']
df = df.set_index('bins')
df_ordered = df.T[order].T.reset_index()
df_ordered

fig2=px.scatter_geo(df_ordered,lon='longitude', lat='latitude',color='bins',
                      opacity=0.5,
                      projection="natural earth")
fig2.show()