5

I need to plot a 3D plot with multiple Linear Regression with 2 features in matplotlib. How can I do that?

this is my code:

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)
Ali AzG
  • 1,861
  • 2
  • 18
  • 28
Sajjad Aemmi
  • 2,120
  • 3
  • 13
  • 25

1 Answers1

3

So you want to plot a 3d plot of your regression model's outcome. In your 3d plot, for each point you have (x, y, z) = (Weight, Volume, PredictedCO2).

Now you can plot it with:

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()

This will give you a plot like this:

enter image description here

Redowan Delowar
  • 1,580
  • 1
  • 14
  • 36
  • I have the same task. I want to fit linear regression model using multiple variable approach. I trained that data with independent variables two (Weight and column) and one dependent variable (CO2). I get the predicted z value of CO2 against each point of weight and volume. I plot the scatter plot. But my task is to generate a fitted straight line that passes through these points in 3d space after I applied regression. I need to fit a straight linear regression line passing through these three axes Weight, Volume, and Predicted CO2. I want to plot a 3D plot with scatter and a straight line. – P_Z May 02 '23 at 18:06
  • A linear regression model is used to fit a data and a straight line passes through these data. That's what I want to achieve "plotting of a 3d fitted straight line" – P_Z May 02 '23 at 18:08