如何在seaborn箱线图中排序绘图

4

以下是一个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)

enter image description here

能否将这些条目按从大到小(或相反)的顺序进行“排名”?在这个图中,如果按从大到小排序,“astrometry”应该是最后一个条目。

2个回答

11

试试这个:

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)

image


7
您可以在 sns.boxplotsns.stripplot 函数中使用 order 参数来对“箱子”进行排序。以下是如何执行此操作的示例(由于“从大到小”的含义不完全清楚,即您想要基于哪个变量对条目进行排序,我假设您希望根据它们的“距离”值之和对它们进行排序,如果您想要基于其他值进行排序,则应该能够编辑解决方案以满足您的需求):
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)

这段修改过的代码(注意在 sns.boxplotsns.stripplot 函数中使用了 order 参数)将会产生以下图像:

有序箱线图


谢谢,order参数运行得很好。我不确定另一个评论去哪了... - ShanZhengYang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接