【问题标题】:colour of geom_bargeom_bar 的颜色
【发布时间】:2012-09-12 16:09:19
【问题描述】:

我无法控制 ggplot 中条形图的颜色

require(mice)
require(ggplot2)
impute <- mice(nhanes, seed = 101)
ldt <-complete(impute,"long", include=TRUE)
ldt$Imputed<-ifelse(ldt$".imp"==0,"Observed","Imputed")

ggplot(ldt[!is.na(ldt$hyp),], aes(x= factor(hyp), colour=Imputed)) + 
  geom_bar() + 
  facet_wrap(~.imp, nrow = 1) +
  scale_y_continuous(expand = c(0,0))

这给出了:

但我想用颜色填充条形,所以我尝试了:

ggplot(ldt[!is.na(ldt$hyp),], aes(x= factor(hyp))) + 
  geom_bar(colour = Imputed) + 
  facet_wrap(~.imp, nrow = 1) +
  scale_y_continuous(expand = c(0,0))

但这给出了错误:

Error in do.call("layer", list(mapping = mapping, data = data, stat = stat,  : 
  object 'Imputed' not found

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    在您的第一次尝试中使用fill=Imputed 而不是colour=Imputed

    ggplot(ldt[!is.na(ldt$hyp),], aes(x= factor(hyp), fill=Imputed)) + 
      geom_bar() + 
      facet_wrap(~.imp, nrow = 1) +
      scale_y_continuous(expand = c(0,0))
    

    您可以改为在geom_bar 中设置fill=Imputed,但您必须将其包装在对aes 的调用中,就像在对ggplot 的调用中一样。

    【讨论】:

      【解决方案2】:

      在原来的审美映射中不要使用colour = Imputed,而是使用fill = Imputed

      ggplot(ldt[!is.na(ldt$hyp),], aes(x= factor(hyp), fill=Imputed)) + 
        geom_bar() + 
        facet_wrap(~.imp, nrow = 1) +
        scale_y_continuous(expand = c(0,0))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        • 2018-06-20
        • 1970-01-01
        相关资源
        最近更新 更多