Seaborn构面网格:向每个plt.plot构面添加水平均值线

时间:2019-11-26 20:07:33

标签: python pandas matplotlib seaborn

我有一个简单的4行1列的构面网格,其中的线图表示构面的不同类别-下图。

#lineplot for each Category over the last three years

g = sns.FacetGrid(dataframe, row="Category", sharey=False, sharex=False, height=2.5, aspect = 3)
g = g.map(plt.plot, 'CREATED_DATE', 'COUNT')

image

如何添加参考线以显示每个构面的平均计数?

2 个答案:

答案 0 :(得分:1)

您可以在每个轴上手动绘制水平线:

g = sns.FacetGrid(df, row="Category", sharey=False, sharex=False, height=2.5, aspect = 3)
g = g.map(plt.plot, 'CREATED_DATE', 'COUNT')

# draw lines:
for m,ax in zip(df.groupby('Category').COUNT.mean(), g.axes.ravel()):
    ax.hlines(m,*ax.get_xlim())

输出:

enter image description here

答案 1 :(得分:1)

仅一行就够了

g = g.map(lambda y, **kw: plt.axhline(y.mean(), color="k"), 'COUNT')

要使线条变为橙色和虚线并添加注释,可以这样做

def custom(y, **kwargs):
    ym = y.mean()
    plt.axhline(ym, color="orange", linestyle="dashed")
    plt.annotate(f"mean: {y.mean():.3f}", xy=(1,ym), 
                 xycoords=plt.gca().get_yaxis_transform(), ha="right")

g = g.map(custom, "Count")