我正在运行一组具有相同自变量但不同因变量的模型,我想在一个图中创建一组系数图,其中每个模型都有自己的面板.以下代码提供了直觉,但在此所有模型都集成到一个图形中,而不是在一个图形中并排放置 3 个独特的面板:
I'm running a set of models with the same independent variables but different dependent variables and would like to create a set of coefficient plots in one figures in which each model gets its own panel. The following code provides intuition but in this all of the models are integrated into one figure rather than have 3 unique panels side-by-side in one figure:
require("coefplot") set.seed(123) dat <- data.frame(x = rnorm(100), z = rnorm(100), y1 = rnorm(100), y2 = rnorm(100), y3 = rnorm(100)) mod1 <- lm(y1 ~ x + z, data = dat) mod2 <- lm(y2 ~ x + z, data = dat) mod3 <- lm(y3 ~ x + z, data = dat) multiplot(mod1,mod2, mod3)生成这个图:
关于如何让它们在一个图形中彼此相邻的面板有什么想法吗?谢谢!
Any thoughts on how to get them to panel next to each other in one figure? Thanks!
推荐答案我之前没有使用过 coefplot 包,但是你可以直接在 ggplot2 中创建系数图>.
I haven't used the coefplot package before, but you can create a coefficient plot directly in ggplot2.
set.seed(123) dat <- data.frame(x = rnorm(100), z = rnorm(100), y1 = rnorm(100), y2 = rnorm(100), y3 = rnorm(100)) mod1 <- lm(y1 ~ x + z, data = dat) mod2 <- lm(y2 ~ x + z, data = dat) mod3 <- lm(y3 ~ x + z, data = dat) ## Create data frame of model coefficients and standard errors # Function to extract what we need ce = function(model.obj) { extract = summary(get(model.obj))$coefficients[ ,1:2] return(data.frame(extract, vars=row.names(extract), model=model.obj)) } # Run function on the three models and bind into single data frame coefs = do.call(rbind, sapply(paste0("mod",1:3), ce, simplify=FALSE)) names(coefs)[2] = "se" # Faceted coefficient plot ggplot(coefs, aes(vars, Estimate)) + geom_hline(yintercept=0, lty=2, lwd=1, colour="grey50") + geom_errorbar(aes(ymin=Estimate - se, ymax=Estimate + se, colour=vars), lwd=1, width=0) + geom_point(size=3, aes(colour=vars)) + facet_grid(. ~ model) + coord_flip() + guides(colour=FALSE) + labs(x="Coefficient", y="Value") + theme_grey(base_size=15)更多推荐
R中的堆栈系数图
发布评论