没有方面的ggplot

时间:2012-09-12 20:41:24

标签: r ggplot2

以下代码,来自@ROLO,回答我之前的问题,产生了3个图:

require(mice)
require(reshape2)
require(ggplot2)
dt <- nhanes
impute <- mice(dt, seed = 23109)

# Obtain the imputed data, together with the original data
imp <- complete(impute,"long", include=TRUE)
# Melt into long format
imp <- melt(imp, c(".imp",".id","age"))
# Add a variable for the plot legend
imp$Imputed<-ifelse(imp$".imp"==0,"Observed","Imputed")

# Plot. Be sure to use stat_density instead of geom_density in order
#  to prevent what you call "unwanted horizontal and vertical lines"
ggplot(imp, aes(x=value, group=.imp, colour=Imputed)) + 
    stat_density(geom = "path",position = "identity") +
    facet_wrap(~variable, ncol=2, scales="free")

enter image description here

我的问题是,我该如何修改它来单独绘制每一个?

1 个答案:

答案 0 :(得分:1)

正如Joran所说,你可以在每个情节中使用一部分数据。

ggplot(imp[imp$variable=="bmi",], aes(x=value, group=.imp, colour=Imputed)) + 
    stat_density(geom = "path",position = "identity")
ggplot(imp[imp$variable=="hyp",], aes(x=value, group=.imp, colour=Imputed)) + 
    stat_density(geom = "path",position = "identity")
ggplot(imp[imp$variable=="chl",], aes(x=value, group=.imp, colour=Imputed)) + 
    stat_density(geom = "path",position = "identity")

或者,您可以将它们放在循环中

library("plyr")
d_ply(imp, .(variable), function(DF) {
    print(ggplot(DF, aes(x=value, group=.imp, colour=Imputed)) + 
        stat_density(geom = "path",position = "identity"))
})

这种方法的缺点是它将所有图形一个接一个地放在一个,所以没有机会在屏幕上看到之前的图形。如果您正在输出PDF(直接或通过类似knitr之类的东西),所有内容都将被编写,并且可以通过这种方式进行查看。