1

我无法控制 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
4

2 回答 2

2

在您的第一次尝试中使用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))

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

在此处输入图像描述

于 2012-09-12T08:00:40.510 回答
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))
于 2012-09-12T08:00:43.787 回答