我正在尝试基于另一个变量创建一个具有渐变颜色背景的折线图(非常类似于此帖子1)。区别在于我有多行基于不同的因子水平。这是我的代码:
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)
这将产生此图
如何将背景色更改为蓝色渐变并为线条使用其他调色板?
非常感谢!
# A dataset
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"))
#########
# Generate colors for the background (see help for 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()