0

Code example is quite simple:

ggplot(mtcars) +
aes(x = cyl, y = mpg, fill = mpg < 34) +
geom_bar(stat = "identity")

You get this: Wrong factor colours

But when you have at least some false samples:

ggplot(mtcars) +
aes(x = cyl, y = mpg, fill = mpg < 20) +
geom_bar(stat = "identity")

THEN, the colours are correct. enter image description here Am I missing something, or is that an inconsistent behaviour and...anybody can help get the correct blue when all is TRUE?

Ploulack
  • 337
  • 1
  • 11
  • Add `scale_fill_discrete(limits = c('TRUE', 'FALSE'))`. I'm pretty sure this is a duplicate, I'll try to find it. – Axeman Aug 18 '17 at 21:01
  • 2
    A discrete color scale uses a palette of discrete colors. It depicts category (factor) variables. The first color in the palette is used for the first factor level, the second for the second, ... If you rely on automatic coercion to factor as in your examples, the factor levels are ordered alphabetically. – Roland Aug 18 '17 at 21:05
  • @Axeman You can try the example, it's quite easy to test...if I add scale_fill_discrete(limits = c('TRUE', 'FALSE')) it's still all red here... – Ploulack Aug 18 '17 at 21:09
  • @Axeman `FALSE` and `TRUE` should be reversed. Apart from that, I got curious too. Is there any way except manually defining the color and except having two factors in the legend to force using the same color for `TRUE/FALSE` factors? – M-- Aug 18 '17 at 21:11
  • 1
    Sorry just put them in the required order: `c(FALSE, TRUE)` – Axeman Aug 18 '17 at 21:11
  • @Roland so how would you reorder the palette, so that when there's TRUE & FALSE values, TRUE is blue, and when there's only TRUE values, TRUE is still blue. – Ploulack Aug 18 '17 at 21:11
  • 1
    You need to either force having both TRUE and FALSE as factor levels and requiring `drop = FALSE`, or you need to set the scale limits manually. – Axeman Aug 18 '17 at 21:12
  • @Masoud Thank you! I'll have to go read about that 'limits' argument for scale_fill – Ploulack Aug 18 '17 at 21:14
  • @Axeman understood, thank you. – Ploulack Aug 18 '17 at 21:14
  • you can check out `?scale_fill_manual`, which gives an example, where you pass in a named vector of the colors. So you can specify your color choices like this `cols <- c("TRUE" = "blue", "FALSE" = "red") ggplot(mtcars) + aes(x = cyl, y = mpg, fill = mpg < 34) + geom_bar(stat = "identity") + scale_fill_manual(values = cols) ` – shaojl7 Aug 21 '17 at 08:38

0 Answers0