[英]Density plots with multiple groups
我試圖從lattice package
生成類似於densityplot()
東西,在使用mice
包多次插補后使用ggplot2
。 這是一個可重復的例子:
require(mice)
dt <- nhanes
impute <- mice(dt, seed = 23109)
x11()
densityplot(impute)
哪個產生:
我想對輸出有更多的控制(我也將它用作ggplot的學習練習)。 所以,對於bmi
變量,我試過這個:
bar <- NULL
for (i in 1:impute$m) {
foo <- complete(impute,i)
foo$imp <- rep(i,nrow(foo))
foo$col <- rep("#000000",nrow(foo))
bar <- rbind(bar,foo)
}
imp <-rep(0,nrow(impute$data))
col <- rep("#D55E00", nrow(impute$data))
bar <- rbind(bar,cbind(impute$data,imp,col))
bar$imp <- as.factor(bar$imp)
x11()
ggplot(bar, aes(x=bmi, group=imp, colour=col)) + geom_density()
+ scale_fill_manual(labels=c("Observed", "Imputed"))
產生這個:
所以它有幾個問題:
invalid argument to unary operator
提供了錯誤invalid argument to unary operator
而且,使用densityplot(impute)
在一行中完成的工作似乎做了很多工作 - 所以我想知道我是否可能完全以錯誤的方式解決這個問題?
編輯 :我應該添加第四個問題,如@ROLO所述:
0.4。 這些圖的范圍似乎不正確。
它之所以是比較復雜的使用GGPLOT2是您正在使用densityplot
從小鼠封裝( mice::densityplot.mids
要精確-看看它的代碼),而不是從自身格。 此函數具有用於繪制內置mice
mids
結果類的所有功能。如果您使用lattice::densityplot
嘗試相同,您會發現它至少與使用ggplot2一樣多。
但不用多說,這里是如何使用ggplot2:
require(reshape2)
# 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")
但正如您所看到的,這些圖的范圍小於densityplot
圖的范圍。 這種行為應該由stat_density
的參數trim
控制,但這似乎不起作用。 修復stat_density
的代碼后,得到以下圖:
仍然與densityplot
原始不完全相同,但更接近。
編輯:要獲得真正的修復,我們需要等待ggplot2的下一個主要版本,請參閱github 。
您可以要求Hadley為此mids類添加fortify方法。 例如
fortify.mids <- function(x){
imps <- do.call(rbind, lapply(seq_len(x$m), function(i){
data.frame(complete(x, i), Imputation = i, Imputed = "Imputed")
}))
orig <- cbind(x$data, Imputation = NA, Imputed = "Observed")
rbind(imps, orig)
}
在繪圖之前,ggplot'強化'非data.frame對象
ggplot(fortify.mids(impute), aes(x = bmi, colour = Imputed,
group = Imputation)) +
geom_density() +
scale_colour_manual(values = c(Imputed = "#000000", Observed = "#D55E00"))
請注意,每個都以'+'結尾。 否則命令將完成。 這就是傳說沒有改變的原因。 以“+”開頭的行導致錯誤。
您可以將fortify.mids的結果融合在一起繪制所有變量
library(reshape)
Molten <- melt(fortify.mids(impute), id.vars = c("Imputation", "Imputed"))
ggplot(Molten, aes(x = value, colour = Imputed, group = Imputation)) +
geom_density() +
scale_colour_manual(values = c(Imputed = "#000000", Observed = "#D55E00")) +
facet_wrap(~variable, scales = "free")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.