【问题标题】:Seaborn regplot: how to truncate regression line and CI?Seaborn regplot:如何截断回归线和 CI?
【发布时间】:2021-07-01 10:22:51
【问题描述】:

我有一个散点图,其中数据的下限为零(两个轴)。然而,当用 lmplot 绘制回归线时,我在 y 轴上得到线和 CI 的负值。有没有办法在 y 轴上绑定 regline 和 CI?

使用的代码:

ax1 = sns.lmplot(x=x, y=y, hue=z, data=df, fit_reg=False, 
             scatter_kws={'s':70}, height=7, aspect=1.2, 
             legend=False, palette=colors)
sns.regplot(x=x, y=y, data=df, scatter=False, ax=ax1.axes[0, 0], color='grey')
ax1.set(ylim=(-2, None))

【问题讨论】:

    标签: python matplotlib plot seaborn


    【解决方案1】:

    您可以用一个大矩形来剪裁直线和置信区间。

    from matplotlib import pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    N = 80
    xs = np.random.uniform(1, 10, N)
    ys = 20 / xs + 2*np.random.uniform(0, 1, N)**4
    df = pd.DataFrame({'x': xs, 'y': ys, 'z': np.random.randint(0, 2, N)})
    g = sns.lmplot(x='x', y='y', hue='z', data=df, fit_reg=False,
                   scatter_kws={'s': 70}, height=7, aspect=1.2,
                   legend=False, palette='turbo')
    ax = g.axes[0, 0]
    sns.regplot(x='x', y='y', data=df, scatter=False, ax=ax, color='grey')
    rect = plt.Rectangle((-1000, 0), 2000, 2000, color='r', alpha=0.2)
    ax.add_patch(rect) # the clipping rectangle needs to be added to the ax to receive the correct transform
    ax.collections[-1].set_clip_path(rect)
    ax.lines[-1].set_clip_path(rect)
    rect.remove() # remove the rectangle again
    ax.relim() # recalculating the limits after removing the rectangle
    ax.set(ylim=(-1, None))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2016-08-07
      • 2021-02-23
      相关资源
      最近更新 更多