[英]How to rank plot in seaborn boxplot?
例如,从https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html中获取以下seaborn箱线图
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)
您可以在sns.boxplot
和sns.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.boxplot
和sns.stripplot
函数中使用order
参数)将产生下图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.