如何解决plotnine绘图时优先按字母顺序排序,无法按Weight列排序的问题?
如何解决plotnine绘图时优先按字母顺序排序,无法按Weight列排序的问题?
嗨,我来帮你排查下这个问题~ 你的代码里有两个关键小问题导致排序不符合预期,咱们一步步来修正:
问题1:丢失了Weight的有序分类属性
你已经把Weight转成了有序分类,但在绘图的aes里又用factor(Weight)把它重新转成了普通因子——这会直接丢掉你之前设置的有序规则,plotnine自然就回到默认排序了。
问题2:Breed默认按字母排序
Breed是字符串类型,plotnine默认会按字母顺序排列它。如果想要它跟着Weight的排序走,需要把Breed也转换成有序分类,用排序后的顺序来指定类别。
修改后的完整代码
import numpy as np import pandas as pd from plotnine import * # 原有数据处理步骤 sorted_weight = traits_n_weights.sort_values(by=["Weight"]) top_weight = sorted_weight.head(70) bins = sorted(top_weight["Weight"].unique()) # 同时处理Weight和Breed的有序分类 top_weight = top_weight.assign( # 保留Weight的有序分类设置 Weight=pd.Categorical(top_weight["Weight"], categories=bins, ordered=True), # 让Breed按照Weight排序后的顺序成为有序分类 Breed=pd.Categorical(top_weight["Breed"], categories=top_weight["Breed"].unique(), ordered=True) ) # 绘图时x直接用Weight,不用再套factor() plot = ggplot(top_weight, aes(x="Weight", y="Breed")) + geom_point() + labs(y="") plot
关键修改点说明
- 去掉
x="factor(Weight)",直接用x="Weight":因为Weight已经是有序分类,plotnine会严格遵循你设定的bins顺序来排列x轴。 - 新增
Breed的有序分类:利用排序后的top_weight里的Breed唯一值作为分类类别,这样y轴的Breed就会跟着Weight的排序走,不再按字母排列啦。
备注:内容来源于stack exchange,提问作者bibi2001
相关产品推荐
相关产品推荐

