Apply color brewer to a single line in ggplot
Asked Answered
C

2

6
library(tidyverse)
library(RColorBrewer)
mtcars %>% 
  count(cyl) %>% 
  ungroup() %>% 
  ggplot(aes(cyl, n)) + 
  geom_line(size = 3) + 
  scale_color_brewer(palette = "Accent")

I'll often have a whole series of graphs with the color theme for each being scale_color_brewer(palette = "Accent"). I want to maintain this theme throughout my .Rmd file, on all graphs. However, this scale_color_brewer() only works if there's multiple lines on each plot.

For the case above (a single line), how do I apply scale_color_brewer(palette = "Accent"), short of specifying the unique color as an argument in geom_line()? I'm hoping there's a better solution than that manual process. Using different themes and having to look up all the different CMYK values gets tedious.

Centurial answered 15/4, 2019 at 14:4 Comment(0)
P
4

You could always set a color aesthetic and just turn off the legend

mtcars %>% 
  count(cyl) %>% 
  ungroup() %>% 
  ggplot(aes(cyl, n, color="A")) + 
  geom_line(size = 3) + 
  scale_color_brewer(palette = "Accent", guide="none")
Paternoster answered 15/4, 2019 at 14:46 Comment(0)
B
8

Two things you can do to take away the tedium are to save the palette(s) you want to keep using to a variable, and set geom defaults. I often do this to keep a couple palettes ready to use throughout a document, like one qualitative and one continuous.

update_geom_defaults takes a list of default arguments for a specified geom, but you can still add to or override those defaults, like below.

library(dplyr)
library(ggplot2)

accent <- RColorBrewer::brewer.pal(7, "Accent")
# item 6 is hot pink
update_geom_defaults("line", list(color = accent[6]))

mtcars %>% 
  count(cyl) %>% 
  ggplot(aes(x = cyl, y = n)) + 
    geom_line()

mpg %>%
  group_by(year) %>%
  summarise(avg_cty = mean(cty)) %>%
  ggplot(aes(x = year, y = avg_cty)) +
    geom_line(size = 2)

mpg %>%
  group_by(year) %>%
  summarise(avg_hwy = mean(hwy)) %>%
  ggplot(aes(x = year, y = avg_hwy)) +
  geom_line(color = accent[1])

As for knowing what each color in a palette is without sorting through hex codes, RColorBrewer::display.brewer.pal is handy, as are similar functions in other packages like rcartocolor. I have a package of utility functions I use a lot where I wrote a function to display blocks of each color in a vector of hex codes, because it is quite tedious otherwise.

Belamy answered 15/4, 2019 at 14:51 Comment(0)
P
4

You could always set a color aesthetic and just turn off the legend

mtcars %>% 
  count(cyl) %>% 
  ungroup() %>% 
  ggplot(aes(cyl, n, color="A")) + 
  geom_line(size = 3) + 
  scale_color_brewer(palette = "Accent", guide="none")
Paternoster answered 15/4, 2019 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.