如何使用matplotlib绘制具有2个特征的3D多元线性回归?

时间:2020-02-16 19:39:54

标签: python matplotlib mplot3d

我需要在matplotlib中绘制具有2个要素的具有多个线性回归的3D图。我该怎么办?

这是我的代码:

import pandas
from sklearn import linear_model

df = pandas.read_csv("cars.csv")

X = df[['Weight', 'Volume']]
y = df['CO2']

regr = linear_model.LinearRegression()

predictedCO2 = regr.predict([scaled[0]])
print(predictedCO2)

1 个答案:

答案 0 :(得分:0)

因此,您想绘制回归模型结果的3d图。在3d图中,每个点的(x,y,z)=(重量,体积,预测的CO2)。

现在您可以使用以下方式进行绘制:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random

# dummy variables for demonstration
x = [random.random()*100 for _ in range(100)]
y = [random.random()*100 for _ in range(100)]
z = [random.random()*100 or _ in range(100)]

# build the figure instance
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='blue', marker='o')

# set your labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

这会给你这样的情节:

enter image description here