Skip to main content
 首页 » 编程设计

python之如何在 seaborn boxplot 中对情节进行排名

2025年05月04日14emanlee

以下面的seaborn箱线图为例,来自https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html

import numpy as np 
import seaborn as sns 
sns.set(style="ticks", palette="muted", color_codes=True) 
 
# Load the example planets dataset 
planets = sns.load_dataset("planets") 
 
# Plot the orbital period with horizontal boxes 
ax = sns.boxplot(x="distance", y="method", data=planets, 
                 whis=np.inf, color="c") 
 
# Add in points to show each observation 
sns.stripplot(x="distance", y="method", data=planets, 
              jitter=True, size=3, color=".3", linewidth=0) 
 
 
# Make the quantitative axis logarithmic 
ax.set_xscale("log") 
sns.despine(trim=True) 

是否可以对条目进行“排名”,从最高到最低(反之亦然)?在此图中,如果从大到小排列,“天体测量”应该是最后一个条目。

请您参考如下方法:

试试这个:

import numpy as np 
import seaborn as sns 
sns.set(style="ticks", palette="muted", color_codes=True) 
 
# Load the example planets dataset 
planets = sns.load_dataset("planets") 
 
ranks = planets.groupby("method")["distance"].mean().fillna(0).sort_values()[::-1].index 
 
# Plot the orbital period with horizontal boxes 
ax = sns.boxplot(x="distance", y="method", data=planets, 
                 whis=np.inf, color="c",  order = ranks) 
 
# Add in points to show each observation 
sns.stripplot(x="distance", y="method", data=planets, 
              jitter=True, size=3, color=".3", linewidth=0, order = ranks) 
 
# Make the quantitative axis logarithmic 
ax.set_xscale("log") 
sns.despine(trim=True)