简体   繁体   中英

Specify gradient background color and separete from line colors (ggplot2)

I am trying to create a line graph with a gradient color background based on another variable (very similar to this post 1 ). The difference is that I have multiple lines that are based on different factor levels. Here is my code:

ggplot(data=cl, aes(x=date, y=value)) +
  geom_rect(aes(xmin=date,xmax=date+1,ymin=min(value),ymax=max(value), 
                fill=StringencyIndex2)) +
  geom_line(aes(colour=dominio), size=1)

And this produces this graph2

How can I change the background color to a blue gradient and use a different color palette for the lines?

Many thanks!

###
# Generate data 
###
set.seed(1)
date <- seq(as.Date("01Jan20", "%d%b%Y"),as.Date("28May20", "%d%b%Y"), by=1)
dts <- data.frame(date=date,
                  value=cumsum(rnorm(length(date))),
                  dominio=sample(LETTERS[1:5],length(date),replace=T),
                  StringencyIndex2=cut(runif(length(date)), breaks=seq(0,1,0.25)))
dts$dominio <- factor(dts$dominio, labels=c("Comercio y ocio","Alimentacion y farmacia",
                                            "Transporte publico","Trabajo","Residencial"))

#########
# Define colors for the background like in scale_fill_gradient
#########
pal <- colorRampPalette(c("#132B43","#56B1F7"))
cols <- pal(length(unique(dts$StringencyIndex2)))

ggplot(data=dts, aes(x=date, y=value)) +
  geom_rect(aes(xmin=date,xmax=date+1,ymin=min(value),ymax=max(value), 
                fill=StringencyIndex2)) +
  geom_line(aes(colour=dominio), size=1) +
  scale_fill_manual(values=cols) +
  #########
  # Define line colors using scale_color_manual  
  #########
  scale_color_manual(values=c("Comercio y ocio"="red",
                              "Alimentacion y farmacia"="white",
                              "Transporte publico"="yellow",
                              "Trabajo"="green",
                              "Residencial"="cyan")) +
  theme_bw()

在此处输入图像描述

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