简体   繁体   中英

ggplot `scale_fill_manual()` alternate colors infinitely

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)))

Something like this?

scale_fill_manual(
     values = c("red", rep_len(c("blue", "green"), length(unique(mpg$fl))-1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM