Reputation: 25
I have a question about shading an area in using R. I have a data table that looks like this:
Now, I want to plot x and y which I can do using plot(x,y, type ='l'). But the question is: How can I shade the area of the plot (from 0 to infinity in y axis) whenever my 'z' value in the data table is 1?
I really appreciate your desire to help..
Thank you so much.
Upvotes: 0
Views: 178
Reputation: 39605
I would suggest next ggplot2
approach. Try creating a reference variable when z==1
so that you can identify the coordinates for x-axis and then use geom_ribbon()
in next way:
library(ggplot2)
#Data
df <- data.frame(x=2:9,
y=(2:9)^2,
z=c(rep(1,5),rep(0,3)))
#Create reference
df$Ref <- ifelse(df$z==1,df$x,NA)
#Plot
ggplot(df,aes(x=x,y=y))+
geom_line()+
geom_ribbon(aes(x=Ref,ymin=0,ymax=Inf),fill='blue',alpha=0.4)
Output:
Other options would be:
#Create reference
df$Ref <- ifelse(df$z==1,df$x,NA)
df$Ref1 <- ifelse(df$z==1,1,NA)
#Option 1
ggplot(df,aes(x=x,y=y))+
geom_line()+
geom_ribbon(aes(x=Ref,ymin=y,ymax=Inf),fill='blue',alpha=0.4)
#Option 2
ggplot(df,aes(x=x,y=y))+
geom_line()+
geom_ribbon(aes(ymin=Ref1,ymax=Inf),fill='blue',alpha=0.4)
Upvotes: 0