python - Plotly:如何自定义图例顺序?
问题描述
我在 Python 中绘制了 scatter_geo 图。
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
Dut 我需要让它们看起来像这样:
till 500
501-600
601-1000
more 1001
解决方案
如果您查看traceorder,您会看到项目从上到下显示,其顺序与"normal"
选项的输入数据相同。所以你可以改变你的输入数据的顺序来得到你想要的:
如果您想指定任意顺序,可以通过在输入数据中定义顺序来实现。指定行顺序可能有点乏味,所以我经常转置数据框,对现在出现在列中的类别进行排序,然后将其转回其原始形式:
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()
推荐阅读
- javascript - JS - 将多个嵌套函数作为带参数的字符串执行
- wolfram-mathematica - 将特定规则应用于 Mathematica 中的持有(或未评估)函数
- mongodb - MongoDB按不存在的数组项查找
- faunadb - 为所有活动项目创建索引
- python - 正则表达式命名组的多个订单
- python-3.x - 从每一行中提取 char 的位置并提供列表中的位置聚合
- c - 二进制网格中的旋转点
- javascript - eslint - 异步箭头函数返回值错误
- spring - Spring Java 应用程序更改如何导致“无法验证连接”Hikari 池错误?
- javascript - 获取产品的 AJAX 收集端点