首页 > 解决方案 > 为多变量回归绘制 3D 图

问题描述

我想使用以下数据绘制带有平面的 3D 图:

在此处输入图像描述

这是数据框的代码:

df_dict = {'area':[2600, 3000, 3200, 3600, 4000, 4100], 
'bedrooms':[3.0, 4.0, 4.0, 3.0, 5.0, 6.0],
'age':[20, 15, 18, 30, 8, 8], 
'price':[550000, 565000, 610000, 595000, 760000, 810000]}

df = pd.DataFrame(df_dict)

这些值存储在 pandas 的 DataFrame 中。

此外,等式是:

在此处输入图像描述

面积x1,卧室x2,年龄x3。

我只能做到以下几点:

在此处输入图像描述

fig = plt.figure(figsize=(12, 8))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(df['area'], df['bedrooms'], df['age'], c='r', marker='o')

ax.set_xlabel('area')
ax.set_ylabel('bedrooms')
ax.set_zlabel('age')

plt.show()

即使这样看起来也不对。如何使用方程式正确绘制平面?

标签: pythonpandasmatplotlibregression

解决方案


您希望绘制的回归方程实际上有 3 个预测变量和 1 个目标变量。绘图price将需要另一个轴,即在 4d 中绘图。这个在 3d 中绘制平面的简化版本可能是一个很好的起点

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

def f(area, bedrooms):
    return(112*area + 23388*bedrooms + 221323)

n = 6
area = np.linspace(2600, 4100, n)
bedrooms = np.linspace(3, 6, n)

X1, X2 = np.meshgrid(area, bedrooms)
Z = f(X1, X2)

fig = plt.figure(figsize = (12, 8))

ax = plt.axes(projection='3d')
ax.plot_surface(X1, X2, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_xlabel('area')
ax.set_ylabel('bedrooms')
ax.set_zlabel('price')
ax.set_title('surface')

这个


推荐阅读