You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python绘制带回归分析的3D平面?代码问题求解

双自变量3D回归可视化问题修正方案

你的代码核心问题出在np.linspace的参数使用错误,导致无法生成完整的平面网格:

  • 原代码中np.linspace([min(x), max(x)], 10)的写法错误,linspace的前两个参数应该是单个数值(区间的起止点),而非列表,这会导致meshgrid生成的数组维度异常,最终只显示两条线而非平面。

以下是修正后的完整代码,同时实现了类似Excel的回归方程、R²值标注效果:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn.linear_model import LinearRegression

# 替换为你的实际数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 4, 5, 6])
z = np.array([3, 5, 7, 9, 11])

fig = plt.figure(figsize=(10,7))
ax = fig.add_subplot(111, projection='3d')

# 绘制原始散点
ax.scatter(x, y, z, color='blue', label='原始数据')

# 训练线性回归模型
model = LinearRegression()
model.fit(np.column_stack((x, y)), z)
coef_x, coef_y = model.coef_
intercept = model.intercept_
r_squared = model.score(np.column_stack((x, y)), z)

# 生成正确的平面网格点
x_plane = np.linspace(min(x), max(x), 20)
y_plane = np.linspace(min(y), max(y), 20)
x_plane, y_plane = np.meshgrid(x_plane, y_plane)
z_plane = coef_x * x_plane + coef_y * y_plane + intercept

# 绘制回归平面
ax.plot_surface(x_plane, y_plane, z_plane, alpha=0.5, color='orange', label='回归平面')

# 添加回归方程和R²标注
equation_text = f'回归方程: z = {coef_x:.2f}x + {coef_y:.2f}y + {intercept:.2f}\nR² = {r_squared:.4f}'
ax.text2D(0.05, 0.95, equation_text, transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.8))

# 设置坐标轴标签
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.legend()

plt.show()

关键修改说明:

  1. 修正网格生成:将np.linspace([min(x), max(x)], 10)改为np.linspace(min(x), max(x), 20),确保生成连续的区间点,再通过meshgrid得到二维网格,从而绘制完整平面。
  2. 添加R²计算:使用model.score()方法计算决定系数,反映回归模型的拟合效果。
  3. 文本标注:通过ax.text2D()在图表角落添加回归方程和R²值,模拟Excel的标注效果。

内容的提问来源于stack exchange,提问作者user23523627

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:13:13