Python plotnine中如何根据另一变量值对类别进行重排序或排序
解决方案
核心原因:Plotnine展示分类变量的x轴顺序由pandas分类变量的categories属性决定,仅对数据集行排序不会改变分类顺序,同时aes()中直接传入列对象而非列名也会导致分类顺序失效。
方法1:提前修改分类变量顺序(修改原数据)
在排序完成后重置分类变量的类别顺序即可:
import numpy as np import pandas as pd from plotnine import * test_df = pd.DataFrame({'catg': ['a','b','c','d','e'], 'val': [3,1,7,2,5]}) test_df['catg'] = test_df['catg'].astype('category') # 排序后重置分类顺序 test_df = test_df.sort_values(by = ['val']).reset_index(drop=True) test_df['catg'] = test_df['catg'].cat.set_categories(test_df['catg']) # 绘图时aes直接传入列名 (ggplot(data = test_df, mapping = aes(x = 'catg', y = 'val')) + geom_line(linetype = 2) + geom_point() + labs(title = 'Weight of Evidence by catg', x = 'catg', y = 'Weight of Evidence') + theme(axis_text_x= element_text(angle = 0)) )
方法2:直接在绘图时用reorder函数(不修改原数据)
Plotnine内置的reorder()函数功能和R的fct_reorder完全一致,直接在aes的x参数中调用即可,无需提前修改数据集:
import numpy as np import pandas as pd from plotnine import * test_df = pd.DataFrame({'catg': ['a','b','c','d','e'], 'val': [3,1,7,2,5]}) test_df['catg'] = test_df['catg'].astype('category') (ggplot(data = test_df, # 直接用reorder按val升序排列catg的顺序 mapping = aes(x = 'reorder(catg, val)', y = 'val')) + geom_line(linetype = 2) + geom_point() + labs(title = 'Weight of Evidence by catg', x = 'catg', y = 'Weight of Evidence') + theme(axis_text_x= element_text(angle = 0)) )
效果对照
- 原错误输出:

- 修正后预期输出:

内容的提问来源于stack exchange,提问作者ViSa
相关产品推荐
相关产品推荐

