colour of geom_bar

2019-08-11 11:25发布

I am having trouble controlling the colour of barplots in 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))

Which gives: enter image description here

But I would like the bars to be filled with the colour, so I tried:

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

But this gives the error:

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

标签: r ggplot2
2条回答
我想做一个坏孩纸
2楼-- · 2019-08-11 11:57

Use fill=Imputed instead of colour=Imputed in your first attempt.

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

You could set fill=Imputed in geom_bar instead, but you'd have to wrap it in a call to aes, as you would in the call to ggplot.

enter image description here

查看更多
Luminary・发光体
3楼-- · 2019-08-11 11:59

Instead of using colour = Imputed in the original aesthetic mapping, use 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))
查看更多
登录 后发表回答