Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply color brewer to a single line in ggplot

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.

like image 440
Display name Avatar asked Apr 15 '19 14:04

Display name


People also ask

How do I change colors in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.

What colors are available in Ggplot?

rgb() → The rgb() function allows to build a color using a quantity of red, green and blue. An additionnal parameter is available to set the transparency. All parameters ranged from 0 to 1.


1 Answers

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.

like image 180
camille Avatar answered Sep 28 '22 01:09

camille