Plotting interaction of two continuous variables with confidence bands in ggplot2
我想为具有连续结果变量的两个连续预测变量生成具有简单斜率和95%置信带的交互图。
我们可以使用ggplot2中的diamonds数据来解决我的问题。我包括将因子变量的清晰度转换为均值中心的数字变量的语法,以便可以回答我的问题。
1 2 3 4 5 6 7 8 9 10 11 | # 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) |
我可以在下面的摘要输出中看到简单斜率的值。但是我不知道如何用置信带绘制它们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 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)) |
我已经知道如何为因子变量和连续变量创建带有置信带的交互图。如果我对克拉的变量进行中位数拆分,您将看到非常像我最终想要得到的图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 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%置信带以及可能的话,用两个连续的预测变量预测的简单斜率着色的数据点,我将不胜感激。
正如MrFlick所建议的那样,您似乎需要3D图表,而ggplot不会为您完成此操作。 在R Graphics Cookbook的13.8节中,Winston Chang给出了一个详细的示例,说明如何使用可能接近您所想的预测表面绘制3D散点图。 通常,这本书特别适合R Graphics和ggplot,因此值得一本。