Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3D scatter plot with a fitted regression 3D plane in R language

Tags:

r

I am trying to plot a 3D Multiple polynomial regression. I have two independent variables (area and number of bedrooms) and one dependent variable (price). Each independent variable has its own polynomial degree (the area has 3 degrees polynomial, and the number of bedrooms has 4 degrees polynomial).

So far, I was only able to plot in 3D with the package "scatterplot3d", but I was not able to create the fitted regression 3D plane in my plot.

My questions: I want to create a 3D graph with the fitted regression 3D plane and the scatter plot, which package should I use? How would the code look like to have the fitted regression 3D plane in my plot (if you have a general idea)?

Thank You for your help :)

Note : I am using r language in r studio cloud.

like image 287
Zach Avatar asked Nov 24 '25 13:11

Zach


1 Answers

Here's an example using plotPlane from the rockchalk package, which uses the persp function "under the hood" but simplifies the details of the plotting operations. See the help for plotPlane (type ?plotPlane) for details on how the function works and the wide range of options for customizing the plot.

library(rockchalk)

m1 = lm(mpg ~ poly(wt,2) + disp, data=mtcars)

old.par = par(mfrow=c(1,2), mar=c(1,1,1,1))

plotPlane(m1, "wt", "disp", pch=16, col=rgb(0,0,1,0.1), drawArrows=TRUE, alength=0, 
          acol="red", alty=1,alwd=1, theta=25, phi=0)
plotPlane(m1, "wt", "disp", pch=16, col=rgb(0,0,1,0.1), drawArrows=TRUE, alength=0, 
          acol="red", alty=1,alwd=1, theta=35, phi=20)

enter image description here

If you have more than two dependent variables in the model, plotPlane will set the additional variables (the ones not being plotted) to their mean (for numeric variables) or mode (for factors). For example:

m2 = lm(mpg ~ poly(wt,2) + disp + poly(hp,2) + poly(wt,2), data=mtcars)

plotPlane(m2, "wt", "disp", pch=16, col=rgb(0,0,1,0.1), drawArrows=TRUE, alength=0, 
          acol="red", alty=1,alwd=1, theta=25, phi=0)
plotPlane(m2, "wt", "disp", pch=16, col=rgb(0,0,1,0.1), drawArrows=TRUE, alength=0, 
          acol="red", alty=1,alwd=1, theta=35, phi=20)

enter image description here

# Reset graphical parameters back to defaults
par(old.par)
like image 183
eipi10 Avatar answered Nov 27 '25 03:11

eipi10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!