Rで重回帰分析の3Dプロット(交互作用あり)を描画

はじめに

重回帰分析の3Dプロットを描画したいという場合があります。 できれば,交互作用をいれた場合といれない場合でも描画したいです。 rglパッケージを利用して,グリグリと動かせる3Dプロットで描画します。

rglパッケージをMacで利用する場合はX11のインストールが必要です。 使用したデータセットはtreesです。

交互作用なし

library(rgl)
df <- trees
fit <- lm(Volume ~ Girth + Height, df)
df$pred <- predict(fit)
Girth <- seq(min(df$Girth),max(df$Girth),len=100)
Height <- seq(min(df$Height),max(df$Height),len=100)
plot.df <- expand.grid(Girth=Girth,Height=Height)
plot.df$z <- predict(fit,newdata=plot.df)
library(reshape2)
z <- dcast(plot.df,Height~Girth,value.var="z")[-1]
open3d(scale=c(1,1,0.2))
points3d(df$Girth,df$Height,df$Volume,col="blue")
surface3d(Girth,Height,as.matrix(z),col="gray",alpha=.2)
apply(df,1,function(row)lines3d(rep(row[1],2),rep(row[2],2),c(log(row[3]),row[4]),col="lightblue"))
axes3d()
title3d(xlab="Girth",ylab="Height",zlab="Volume")

交互作用あり

library(rgl)
df <- trees
fit <- lm(Volume ~ Girth * Height, df)
df$pred <- predict(fit)
Girth <- seq(min(df$Girth),max(df$Girth),len=100)
Height <- seq(min(df$Height),max(df$Height),len=100)
plot.df <- expand.grid(Girth=Girth,Height=Height)
plot.df$z <- predict(fit,newdata=plot.df)
library(reshape2)
z <- dcast(plot.df,Height~Girth,value.var="z")[-1]
open3d(scale=c(1,1,0.2))
points3d(df$Girth,df$Height,df$Volume,col="blue")
surface3d(Girth,Height,as.matrix(z),col="gray",alpha=.2)
apply(df,1,function(row)lines3d(rep(row[1],2),rep(row[2],2),c(log(row[3]),row[4]),col="gray"))
axes3d()
title3d(xlab="Girth",ylab="Height",zlab="Volume")

プロットの例

左側が交互作用なし,右側が交互作用ありです。交互作用ありだと,捻れた面になっているのがわかります。 f:id:cognition:20190611173834p:plain

参考

stackoverflow.com

kohske.github.io

www.dataquest.io