【问题标题】:How to plot a mean line on a displot?如何在分布图上绘制平均线?
【发布时间】:2021-01-05 05:31:38
【问题描述】:

我正在尝试使用 displot 绘制平均线。我正在尝试复制 this 示例,但出现错误。

    from matplotlib import pyplot

g = sns.displot(data=df, x='age', kind="kde", hue="attrition", palette="crest", fill=True,alpha=.7, linewidth=0,)

g.fig.set_figwidth(15)
g.fig.set_figheight(5)
kdeline = g.lines[0]

mean = x.mean()
height = np.interp(mean, kdeline.get_xdata(), kdeline.get_ydata())
g.vlines(mean, 0, height, color='crimson', ls=':')
g.set_ylim(ymin=0)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-86084b5eb03a> in <module>
      5 g.fig.set_figwidth(15)
      6 g.fig.set_figheight(5)
----> 7 kdeline = g.lines[0]
      8 mean = x.mean()
      9 height = np.interp(mean, kdeline.get_xdata(), kdeline.get_ydata())

AttributeError: 'FacetGrid' object has no attribute 'lines'  

【问题讨论】:

    标签: python python-3.x matplotlib seaborn


    【解决方案1】:

    您可以使用plt.axvline(mean)。请参阅以下带有 planets 数据集的示例:

    from matplotlib import pyplot
    import seaborn as sns
    df = sns.load_dataset('planets')
    g = sns.displot(data=df, x='year', kind="kde", hue="method", palette="crest", fill=True,alpha=.7, linewidth=0,)
    g.fig.set_figwidth(15)
    g.fig.set_figheight(5)
    mean = df['year'].mean()
    plt.axvline(mean)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-09
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多