Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot `scale_fill_manual()` alternate colors infinitely

Tags:

r

ggplot2

My first code chunk works fine, although my throwaway value of 999 is the opposite of elegant. I'm trying to get the first bar red, then alternate blue and green. Probably not the best way to alternate my blue and green colors but it works.

# FIRST CODE CHUNK
library(tidyverse)
ggplot(mpg, aes(fl)) + 
  geom_bar(aes(fill = fl)) + 
  scale_fill_manual(
    values = c("red", rep(c("blue", "green"), 999))
  )

I wanted to scale_fill_manual() and just recycle the blue and green infinitely but that doesn't work. I get the "5 needed only 3 provided" error.

# SECOND CODE CHUNK
ggplot(mpg, aes(fl)) + 
  geom_bar(aes(fill = fl)) + 
  scale_fill_manual(
    values = c(red, c("blue", "green"))
  )

How can I recycle the blue and green colors in my scale_fill_manual() command? I imagine it'd be something like

scale_fill_manual(values = c(red, rep(c("blue", "green"), recycle.infinite)))
like image 521
stackinator Avatar asked Nov 02 '18 17:11

stackinator


1 Answers

Something like this?

scale_fill_manual(
     values = c("red", rep_len(c("blue", "green"), length(unique(mpg$fl))-1))
like image 106
iod Avatar answered Nov 08 '22 20:11

iod