How can I fill under only one line among multiple lines using ggplot2?

I have the following code, and I would like to fill the curve area under only the blue line. How can I do that using the ggplot2. I inserted the filled options, but it is not working. My sample code is as follow:

library(dplyr)
library(lubridate)
library(reshape2)
library(ggplot2)

data1 = data2 = data3
nmonths = 25
x = seq(as.Date("1993/1/1"), by = "month", length.out = nmonths)
data1=c(0,17.15,21.06,19.20,11.31,11.19,9.86,9.97,13.72,14.82,11.19,9.86,9.97,13.72,14.82,18.50,35.72,64.55,21.54,67.92,26.23,22.09,19.11,17.85,18.07)
data2=c(0,10.82,10.20,9.89,9.90,9.95,9.84,9.61,9.26,8.91,8.67,8.59,8.97,10.54,12.39,14.10,6.23,17.36,17.85,17.79,17.26,16.74,17.09,18.06,19.13)
data3=c(67.64,63.66,53,30,26.61,22.07,19.75,25.97,31.59,37.15,57.53,118.19,36.51,77.63,41.73,30.04,26.05,20.70,19.91,32.89,67.25,32.11,70.19,56.48,38.25)

data = cbind(data1,data2,data3)
data = as.data.frame(data)
data = cbind(x, data)

cols = c("Months","data1","data2","data3")
colnames(data) = cols

datamergedMelted <- reshape2::melt(data, id.var='Months')

p <- ggplot(datamergedMelted, 
            aes(x=Months, y=value, col=variable, linetype=variable,
                size=variable,fill=variable)) + 
  geom_area(data=datamergedMelted,color=NA,
            fill=NA,alpha=0.2)+
  geom_line()+
  scale_fill_manual("",values=c("red", "red","red"))+
  scale_color_manual("",values = c("red", "blue", "black")) + 
  scale_linetype_manual("",values = c(1, 1, 4))+
  scale_size_manual("",values=c(1.2,1.3,0.5))+
  geom_point(aes(colour=factor(variable),shape=factor(variable)),size=1.5)+
  scale_shape_manual("", values=c(NA,NA,19))+
  ylab("Levels (mm)")+
  theme(legend.position="top")

print(p)

Image screenshot

Upvotes: 2

Views: 358

Answers (1)

Z.Lin
Z.Lin

Reputation: 29095

You can further filter the data passed to the geom_area layer. You can do likewise for the geom_point layer, too, rather than map NA values to the corresponding scale:

ggplot(datamergedMelted, 
       aes(x = Months, y = value, 
           colour = factor(variable), linetype = factor(variable),
           size = factor(variable))) + 

  geom_area(data = . %>% filter(variable == "data2"),
            color = NA, fill = "black", alpha = 0.5, show.legend = FALSE)+
  geom_line()+
  geom_point(data = . %>% filter(variable == "data3"),
             shape = 19, size = 1.5)+

  scale_color_manual("", values = c("red", "blue", "black")) + 
  scale_linetype_manual("", values = c(1, 1, 4))+
  scale_size_manual("", values=c(1.2,1.3,0.5))+

  ylab("Levels (mm)")+
  theme(legend.position="top")

plot

Upvotes: 0

Related Questions