Issue
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))
Solution
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()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.