Frage

The following code, from @ROLO in answer to my earlier question generates 3 plots:

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

My question is, how do I modify this to plot each one individually ?

War es hilfreich?

Lösung

As Joran said, you can just use a subset of the data in each plot.

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")

Alternatively, you could put these in a loop

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

The downside of this approach is that it puts all the plots out one right after the other so there is no chance to see the previous ones on the screen. If you are outputting to a PDF (directly or via something like knitr), all will get written and can be seen that way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top