【问题标题】:barplots in ggplot from `mids` object来自`mids`对象的ggplot中的条形图
【发布时间】:2012-09-11 17:46:39
【问题描述】:

尽管已经使用了 ggplot 几次,但我真的很难在这个问题上取得任何进展。我想如果不尝试使用 ggplot 来解释我想做什么是最容易的,下面的内容也很丑陋,但这是我目前能做到的最好的:(

require(mice)
impute <- mice(nhanes, seed = 101)

counts <- table(nhanes$hyp)
barplot(counts, main="hyp", xlab="observed")

x11()
counts <- table(complete(impute,1)$hyp)
barplot(counts, main="hyp", xlab="Imputation 1")

x11()
counts <- table(complete(impute,2)$hyp)
barplot(counts, main="hyp", xlab="Imputation 2")

x11()
counts <- table(complete(impute,3)$hyp)
barplot(counts, main="hyp", xlab="Imputation 3")

x11()
counts <- table(complete(impute,4)$hyp)
barplot(counts, main="hyp", xlab="Imputation 4")

x11()
counts <- table(complete(impute,5)$hyp)
barplot(counts, main="hyp", xlab="Imputation 5")

我想创建一个漂亮的网格图,在 ggplot 中显示这些条形图 - 例如,1 行 6 个,在 y 轴上都具有相同的比例,以便可以轻松地比较它们。

我想我应该使用ldt &lt;-complete(impute,"long", include=TRUE),然后使用melt(ldt, c(".imp",".id","hyp")),但我就是不知道在那之后如何调用ggplot :(

请注意,我的真实数据中有许多不同的变量,这仅适用于分类变量。我在想我可以创建一个函数,然后使用sapply 运行它,但只能在分类列上运行?但我不知道该怎么做!

【问题讨论】:

    标签: r ggplot2 melt r-mice


    【解决方案1】:

    几点

    1. 您需要将hyp 或相关变量作为一个因素。最容易删除 执行此操作之前的 NA 值。
    2. facet_wrap(一个变量)或facet_grid(一个或多个变量)将为您安排好图表。

    例如

    ldt <-complete(impute,"long", include=TRUE)
    
    ggplot(ldt[!is.na(ldt$hyp),], aes(x= factor(hyp))) + 
      geom_bar() + 
      facet_wrap(~.imp, nrow = 1) +
      xlab('Observed') +
      scale_y_continuous(expand = c(0,0))
    

    长格式

    现在你想要facet_gridscales = 'free_y'

    all_long <- melt(ldt, c(".imp",".id","hyp"))
    ggplot(all_long[!is.na(all_long$hyp),], aes(x= factor(hyp))) + 
      geom_bar() + 
      facet_grid(variable ~.imp, scales = 'free_y') +
      xlab('Observed') +
      scale_y_continuous(expand = c(0,0))
    

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 1970-01-01
      • 2014-01-24
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      相关资源
      最近更新 更多