绘制类别意味着在 seaborn 分类图中

Plotting category means in seaborn categorical plot

我有一个图,x 轴上有定性变量,每个类别的垂直散点使用 sns.stripplot。我想指出每个类别的平均值。也许是每个类别的平均 y 值处的短水平线。我该怎么做?

您可以使用 matplotlib.pyplot.hlines 对线条的宽度和位置进行一些簿记。这是一个使用 seaborn tips 数据集

的示例
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

tips = sns.load_dataset("tips")
sns.stripplot(x="day", y="total_bill", data=tips)
labels = [e.get_text() for e in plt.gca().get_xticklabels()]
ticks = plt.gca().get_xticks()
w = 0.1
for day, idx in enumerate(labels):
    idx = labels.index(day)
    plt.hlines(tips[tips['day'] == day]['total_bill'].mean(), ticks[idx]-w, ticks[idx]+w)
plt.show()


一些解释

labels = [e.get_text() for e in plt.gca().get_xticklabels()]

sns.stripplot自动生成的ticklabels中提取文本,这比tips['day'].unique()更有用,因为标签的顺序不一定与[=17=返回的顺序一致].这是因为如果未指定 order 参数,则顺序将为

[...] inferred from the the data objects.

plt.hlines(tips[tips['day'] == day]['total_bill'].mean(), ticks[idx]-w, ticks[idx]+w)

围绕 'strip' 的中心绘制长度为 w*2 的水平线,高度为 'total_bill' 列的平均值,其中 'day' 的值行等于当天。