如何在Python中绘制带X-Y轴分布曲线的线性回归图
实现带轴分布曲线的线性回归图
直接上可运行的代码,用matplotlib做布局,seaborn画分布曲线,sklearn做线性回归:
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression # 生成模拟数据 np.random.seed(42) x = np.random.rand(100) * 10 y = 2 * x + np.random.randn(100) * 2 # 拟合线性回归模型 X = x.reshape(-1, 1) model = LinearRegression() model.fit(X, y) y_pred = model.predict(X) # 创建布局:主图+上方X分布+右侧Y分布 fig = plt.figure(figsize=(10, 8)) # 主图:散点+回归线 ax_main = fig.add_axes([0.1, 0.1, 0.6, 0.6]) ax_main.scatter(x, y, alpha=0.6, label='原始数据') ax_main.plot(x, y_pred, color='red', linewidth=2, label=f'回归线: y={model.coef_[0]:.2f}x + {model.intercept_:.2f}') ax_main.set_xlabel('X轴') ax_main.set_ylabel('Y轴') ax_main.legend() ax_main.grid(alpha=0.3) # 上方X轴分布曲线 ax_x_dist = fig.add_axes([0.1, 0.75, 0.6, 0.2]) sns.kdeplot(x, ax=ax_x_dist, fill=True, color='blue') sns.histplot(x, ax=ax_x_dist, kde=False, color='blue', alpha=0.3) ax_x_dist.set_xlim(ax_main.get_xlim()) ax_x_dist.set_xticks([]) ax_x_dist.set_yticks([]) ax_x_dist.set_ylabel('') # 右侧Y轴分布曲线 ax_y_dist = fig.add_axes([0.75, 0.1, 0.2, 0.6]) sns.kdeplot(y, ax=ax_y_dist, fill=True, color='green', vertical=True) sns.histplot(y, ax=ax_y_dist, kde=False, color='green', alpha=0.3, orientation='horizontal') ax_y_dist.set_ylim(ax_main.get_ylim()) ax_y_dist.set_xticks([]) ax_y_dist.set_yticks([]) ax_y_dist.set_xlabel('') plt.show()
关键说明
- 用
fig.add_axes()手动控制子图位置,确保主图、顶部分布、右侧分布的布局对齐 - 顶部分布用水平的KDE+直方图,右侧用垂直方向的(通过
vertical=True/orientation='horizontal'实现) - 同步分布子图和主图的轴范围,保证数据对齐
- 隐藏分布子图的刻度,避免视觉干扰
如果你的数据是真实数据集,只需要替换x和y的数据源即可,逻辑完全通用。
内容的提问来源于stack exchange,提问作者jankma15
相关产品推荐
相关产品推荐

