Seaborn刻面网格:为每个plt.p添加水平平均线

2024-04-24 20:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的刻面网格,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

如何添加一条显示每个面平均计数的参考线?你知道吗


Tags: thefalse网格for类别overlastthree
2条回答

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

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

只要一行就够了

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")

相关问题 更多 >