简体   繁体   中英

Seaborn regplot: how to truncate regression line and CI?

I have a scatterplot where the lower limit of the data is zero (both axes). However when plotting the regression line with lmplot I get negative values for the line and the CI in the y-axis. Is there a way to bound regline and CI in the y-axis?

Code used:

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

在此处输入图片说明

You can clip both the line and the confidence interval with a large rectangle.

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

sns.regplot 与剪切回归线和 CI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM