以图形方式显示 Seaborn 群体图上的平均值

Displaying Averages Graphically on Seaborn Swarm Plots

提问人:Andrea 提问时间:4/7/2021 更新时间:4/7/2021 访问量:2063

问:

假设我有以下 seaborn swarmplot:

import seaborn as sns

sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x="day", y="total_bill", data=tips)

swarmplot

在图上显示这些群中的每一个的平均值的简单方法是什么,也许使用不同的符号,例如“X”?

蟒蛇 Seaborn 平均 群图

评论


答:

1赞 retsetera 4/7/2021 #1

要在 Python 中获取值的平均值,您可以执行以下操作

def avg(arr): # arr is a list of values to get the average of
   return sum(arr) / len(arr)
3赞 JohanC 4/7/2021 #2

您可以使用 pandas' 来聚合均值。然后绘制它们。出于某种原因,散点图会重置视图限制。您可以保存和之前,然后重置它们。要将散点图放在群图之上,可以设置一个 zorder(在 Seaborn 0.11.1 中尝试):groupbysns.scatterplotxlimylim

import seaborn as sns

sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x="day", y="total_bill", data=tips)
df_means = tips.groupby("day")["total_bill"].agg("mean").reset_index()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
sns.scatterplot(x="day", y="total_bill", marker='X', color='black', s=100, zorder=3, ax=ax, legend=False, data=df_means)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt.show()

swarmplot with means

PS:获得所需视图限制的另一种解决方法是首先绘制均值(但至少为 4 个),然后绘制群图:zorder

ax = sns.scatterplot(x="day", y="total_bill", marker='X', color='black', s=100, zorder=4, legend=False, data=df_means)
sns.swarmplot(x="day", y="total_bill", data=tips, ax=ax)

另一种方法是在箱线图的顶部绘制 swarmplot,如 swarmplot 手册页上的最后一个示例所示。

评论

0赞 Andrea 4/8/2021
谢谢你@JohanC。知道为什么使用您的确切代码为周日群图呈现白色“X”,而为所有其他图呈现黑色“X”吗?(我也在使用 Seaborn 版本 0.11.1)