You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Plotly Express中按x轴最大值降序排列y轴类别

Plotly Express散点图按x轴最大值对y轴类别降序排列

我需要在Plotly Express散点图中,基于x轴Criminal_Case的最大值对y轴Party的类别进行降序排列,但多次尝试都未成功。

数据加载代码

import pandas as pd
import plotly.express as px

df = pd.read_csv('https://raw.githubusercontent.com/johnsnow09/Party_Criminal_Records/main/For_Analysis_in_R.csv')

失败的尝试

  • 仅设置y轴为类别类型,未实现按最大值排序
px.scatter(df,x = 'Criminal_Case', y = 'Party').update_layout(height = 1000).update_yaxes(type='category')
  • 按类别名称升序排列,不符合需求
px.scatter(df,x = 'Criminal_Case', y = 'Party').update_layout(height = 1100).update_yaxes(categoryorder='category ascending')
  • 用箱线图按总计升序,不是按最大值排序
px.box(df,x = 'Criminal_Case', y = 'Party').update_layout(height = 1000).update_yaxes(categoryorder='total ascending')

R中已实现的代码

df %>% ggplot(aes(x = Criminal_Case, y = fct_reorder(Party, Criminal_Case, .fun = max) )) + geom_point()

解决方案

Plotly Express没有直接对应fct_reorder的参数,需要先在Pandas中预处理数据,按每个Party对应的Criminal_Case最大值对类别排序,再传入绘图函数。

完整实现代码:

import pandas as pd
import plotly.express as px

# 加载数据
df = pd.read_csv('https://raw.githubusercontent.com/johnsnow09/Party_Criminal_Records/main/For_Analysis_in_R.csv')

# 计算每个Party的Criminal_Case最大值,生成降序排序的政党列表
party_max_case = df.groupby('Party')['Criminal_Case'].max().sort_values(ascending=False)

# 将Party列转为有序类别,指定排序规则
df['Party'] = pd.Categorical(df['Party'], categories=party_max_case.index, ordered=True)

# 绘制散点图
fig = px.scatter(df, x='Criminal_Case', y='Party', height=1000)
fig.show()

代码说明

  1. 生成排序键:通过groupby+max获取每个政党的最大刑事案件数,再降序排序得到目标顺序的政党列表。
  2. 转换有序类别:用pd.Categorical将Party列设置为有序类别,指定categories为排序后的列表,Plotly会自动遵循这个顺序渲染y轴。
  3. 绘制图表:直接使用预处理后的DataFrame绘图,即可实现和R中fct_reorder一致的效果。

内容的提问来源于stack exchange,提问作者ViSa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:12:39