Why is ggplot using default colors when others are specified?

若如初见. 提交于 2019-12-01 08:49:45

I don't think you can explicitly set colors in aes; you need to do it in scale_fill_manual, as in the example below:

ggplot(dist.x, aes(x = sim_con)) +
  geom_histogram(colour = "black", binwidth = .01,aes(fill=(sim_con==1.55))) + 
  scale_fill_manual(values=c('TRUE'='darkgreen','FALSE'='firebrick')) +
  theme(legend.position="none")

You're so close!

In your code above, ggplot is interpreting your fill as variables in your data set - factor darkgreen and factor firebrick - and doesn't have any way of knowing that those labels are colors, not, say, names of animal species.

If you add scale_fill_identity() to the end of your plot, as below, it will interpret those strings as colors (the identity), not as features of the data.

One benefit of this approach vs @marat's excellent answer above: if you have a complex plot (say, using geom_segment(), with a starting value and an ending value for each observation) and you want to apply two fill scales on your data (one scale for the start value and a different scale for the end value) you can do the conditional logic in the data processing step, then use scale_fill_identity() to color each observation accordingly.

ggplot(
  data=dist.x,
  aes(
    x = sim_con,
    fill = ifelse(dist.x$sim_con==1.55, "darkgreen", "firebrick")
  )
) +
geom_histogram(
  colour = "black",
  binwidth = .01
) +
theme(legend.position="none") +
scale_fill_identity()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!