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

Sha*_*ang 3 python matplotlib pandas seaborn

以下面的 seaborn boxplot 为例,来自https://stanford.edu/~mwaskom/software/seaborn/examples/horizo​​ntal_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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

Mer*_*lin 8

尝试这个:

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)
Run Code Online (Sandbox Code Playgroud)

图片


bbk*_*glb 7

您可以使用和函数中的order参数来订购您的“盒子”。这是一个如何执行此操作的示例(因为“从最高到最低”的含义尚不完全清楚,即您想根据哪个变量对条目进行排序,我假设您想根据总和对它们进行排序的“距离”值,如果您想根据不同的值对它们进行排序,您应该能够编辑解决方案以满足您的需求):sns.boxplotsns.stripplot

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")

# Determine the order of boxes
order = planets.groupby(by=["method"])["distance"].sum().iloc[::-1].index

# Plot the orbital period with horizontal boxes
ax = sns.boxplot(x="distance", y="method", data=planets,
                 order=order, whis=np.inf, color="c")

# Add in points to show each observation
sns.stripplot(x="distance", y="method", data=planets, order=order,
              jitter=True, size=3, color=".3", linewidth=0)


# Make the quantitative axis logarithmic
ax.set_xscale("log")
sns.despine(trim=True)
Run Code Online (Sandbox Code Playgroud)

这个修改后的代码(注意和函数中order参数的使用)将产生下图:sns.boxplotsns.stripplot

有序箱线图