Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

r - How to have each facet be a different color in Ggplot

Below is the sample data, manipulations, and ggplot code. My question is how I would dictate the backgroound color for each of these facets or items? I know how to make it all one color or such but am fumbling around trying to find out how to make them three separate colors?

#Data generation
Month1 <- c(201811,201812,20191,20192,20193,20194,20195,20196,
        20197,20198,20199,201910,201911,201912,20201
        ,20202,20203,20204,20205,20206,20207
        ,20208,20209,202010,202011)
Rate <- 
c(3.2,3.3,3.4,3.1,3.0,3.1,2.9,2.6,2.5,2.3,2.1,1.6,1.7,1.5,1.7,1.1,-0.4,
-19.5,-17.6,-10.5,-9.6,-9.1,-8.6,-8.0,-7.7)

 cesyoym <- data.frame(Month1,Rate)

#Chart
library(ggplot2)
library(dplyr)
library(lubridate)
library(scales)
library(odbc)

 ##date

 

 linechartm<-cesyoym %>% 
 mutate(year = substr(as.character(Month1),1,4),
     month = substr(as.character(Month1),5,7),
     date = as.Date(paste(year,month,"1",sep ="-"))) %>%  
 ggplot() + 
 geom_line(aes(x = date, y = Rate)) +
 geom_rect(xmin = -Inf, ymin = -Inf, xmax = Inf, ymax = Inf, alpha = 0.1, aes(fill = year)) +
 facet_wrap(~year, scales = "free_x") +
 scale_y_continuous(labels = scales::percent) +
 scale_x_date(date_breaks="1 month", date_labels="%b
") + 
 ggtitle("Employment  Growth (%)") +
 theme(panel.grid.major = element_blank(),
    axis.text.x = element_text(angle = 90, size = rel(0.6)),
    panel.spacing = unit(0, "lines"),
    strip.placement = 'outside',
    strip.background = element_blank()) +
 scale_fill_brewer(palette = "Spectral") + 
 guides(fill = FALSE)

print(linechartm)
question from:https://stackoverflow.com/questions/65907058/how-to-have-each-facet-be-a-different-color-in-ggplot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...