我想生成一个具有简单斜率的相互作用图,并为具有连续结果变量的两个连续预测变量生成95%置信区间。
我们可以使用ggplot2中的钻石数据来解决我的问题。我包含了将因子变量 clear 转换为数字,以中心为中心的变量的语法,以便我可以回答我的问题。
# load package
library(ggplot2)
# rename data from ggplot2
d <- diamonds
# recode clarity from a factor variable into a numeric variable
levels(d$clarity)
library(plyr)
mapvalues(d$clarity, from = c("I1" , "SI2" , "SI1" , "VS2" , "VS1" , "VVS2" , "VVS1" , "IF"),
to = c("1", "2", "3", "4", "5", "6", "7", "8"))
d$clarity_n <- as.numeric(d$clarity)
我可以在下面的摘要输出中看到简单斜率的值。但我无法弄清楚如何用自信的乐队来绘制它们。
# create variables for simple effects
d$carat_MC <- d$carat - mean(d$carat, na.rm=T)
d$clarity_nMC <- d$clarity_n - mean(d$clarity_n, na.rm=T)
d$clarityPLUS_1sd <- d$clarity_nMC + sd(d$clarity_n, na.rm=T)
d$clarityMINUS_1sd <- d$clarity_nMC - sd(d$clarity_n, na.rm=T)
# create a small subset of 500
d <- d[sample(1:nrow(d), 500,replace=FALSE),]
# model the interaction and simple slopes
summary(lm(price~carat_MC*clarity_nMC, data = d))
# simple effect of increased carat for less clear diamonds
summary(lm(price~carat_MC*clarityPLUS_1sd, data = d))
# simple effect of increased carat for more clear diamonds
summary(lm(price~carat_MC*clarityMINUS_1sd, data = d))
我已经知道如何用因子变量和连续变量的置信带创建交互图。如果我将 carat 的变量中位数分割,你会看到一个非常类似于我最终得到的情节:
# create a new factor variable based on the median split
d$clarity_nMS[ d$clarity_nMC < median(d$clarity_nMC) ] <- -1
d$clarity_nMS[ d$clarity_nMC > median(d$clarity_nMC) ] <- 1
d$clarity_nMS <- as.factor( d$clarity_nMS )
# Begin plotting
ex <- ggplot(d, aes(carat_MC, price, color = clarity_nMS))
# jitter the scatter plot
ex <- ex + layer(geom = "point",
position = position_jitter(w = 0.1, h = 0.1))
# Add plot lines with confidence intervals.
ex <- ex + geom_smooth(method="lm", se=TRUE , fullrange=TRUE)
ex
如果我能用简单的斜率,95%置信带以及如果可能的话,他们为两个连续预测变量预测的简单斜率着色的数据点,我将不胜感激。
答案 0 :(得分:0)
正如MrFlick建议的那样,你似乎需要一个3D图表,ggplot不会为你做这个。在R Graphics Cookbook的第13.8节中,Winston Chang有一个详细的例子,说明如何使用可能与您想象的接近的预测表面进行3D散点图。一般来说,本书特别适合R Graphics和ggplot,因此可能值得获取副本。