2

以下代码来自@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")

在此处输入图像描述

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

4

1 回答 1

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),所有内容都将被写入并以这种方式显示。

于 2012-09-13T20:55:41.847 回答