python - 为多变量回归绘制 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。
m1
是 112,m2
是 23388,m3
是 -3231b
是 221323
我只能做到以下几点:
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()
即使这样看起来也不对。如何使用方程式正确绘制平面?
解决方案
您希望绘制的回归方程实际上有 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')
推荐阅读
- regex - 试图从 CSV 中过滤掉唯一的 post_ids
- powershell - 我们如何使用“ls”命令将文件列表从 FTP 附加到本地文件?
- node.js - 如何配置CKEditor以显示居中的粘贴图像?
- xml - 使用带有管道符号的 xpath 搜索 XML |
- php - laravel 渴望加载自我关系
- python - 得到 200 响应而不是 302
- c# - 如何防止 Visual Studio 在更深层次的异常中断后中断所有等待
- javascript - 如何从浏览器使用用户的地理位置?Javascript Vue
- autodesk-forge - 我可以确定用户是否是合同经理吗?
- python - 在 MSYS2 下运行(并读取文件)时,re.search 出人意料地以 None 结束?