library(tidyverse)
library(RColorBrewer)
mtcars %>%
count(cyl) %>%
ungroup() %>%
ggplot(aes(cyl, n, color = "A")) +
geom_line(size = 2) +
# scale_color_brewer(palette = "Accent", guide = "none") + # line 8
scale_color_brewer(palette = "Accent", direction = -1, guide = "none") +
NULL
I thought that the direction = -1
argument of ggplot would reverse color scales. Whether I turn this argument on or off I still get the same plot shown below.
I would think leaving the argument off would give me the graph shown above, as green is the first color of Accent
. If I turn on the direction = -1
argument I'd expect the geom_line()
to use the last Accent
color, which is dark grey, yet this is not what happens.
How do I properly reverse the color scales to get dark grey to show up first? I know I could simply use geom_line(aes(color = "dark grey"))
but I'd rather an answer to this question, opposed to that 'simplest solution'.
The direction
argument takes the colors that are assigned to the scale and flips them (so the one assigned to the last value in the scale is assigned to the first). It does not change which colors are assigned to the scale. You see no effect since there is only one possible value for color, so reversing the scale causes no change. Compare these 2 examples:
ggplot(diamonds, aes(x = price, fill = cut)) +
geom_histogram(position = "dodge", binwidth = 1000) +
scale_fill_brewer(palette='Accent')
ggplot(diamonds, aes(x = price, fill = cut)) +
geom_histogram(position = "dodge", binwidth = 1000) +
scale_fill_brewer(palette='Accent', direction = -1)
You can see that the colors chosen are the same, only the order they're assigned to cut
changes.
If you want to change the order of the colors chosen, you can use scale_color_manual
, pass in the palette using brewer.pal
, and then flip and/or subset it there as desired:
mtcars %>%
count(cyl) %>%
ungroup() %>%
ggplot(aes(cyl, n, color = "A")) +
geom_line(size = 2) +
scale_color_manual(values = rev(brewer.pal(8, 'Accent')))