【问题标题】:ggplot without facet没有刻面的ggplot
【发布时间】:2012-09-12 20:41:23
【问题描述】:

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

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

【问题讨论】:

  • 这只是一个评论,以便@ROLO 得到通知,谁写了这段代码来回答我之前的问题。
  • 只需在每个数据子集上精确绘制三次?
  • @joran 谢谢!效果很好 - 我刚刚在调用 ggplot 之前做了imp &lt;- imp[imp$variable=='bmi',],其他人也这样做了

标签: r ggplot2 r-mice


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2018-11-10
    • 1970-01-01
    • 2018-02-09
    • 2015-01-04
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多