Reputation: 143
I am plotting some results of an analysis, in this case I am trying to fill with color the area bellow the black line which is a variable threshold. I have done something similar with geom_ribbon
but considering a fixed threshold.
This is the data I am using:
df <- data.frame(month= seq(560,624,1),
US= c(0.67,0.71,1.49,3.47,8.13,12.13,10.52,9.33,5.48,2.72,1.74,
0.16,0.04,0.15,0.76,0.94,10.60,26.50,15.09,17.93,
15.68,11.69,7.00,3.68,0.46,0.55,1.21,4.14,12.73,
10.24,10.89,22.13,18.76, 18.99,9.76,2.24,0.92,0.29,
0.38,4.92,4.17,2.29,1.92,1.69, 14.87,12.32,2.00,0.67,
0.12,0.06,0.80,4.41,6.70,18.61,7.21,43.62,23.64,12.83,
6.00,2.16,0.69,0.16,3.18,8.87,16.45),
lim= c(0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33,4.34,2.07,
1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33,4.34,
2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,8.33,
4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,6.21,
8.33,4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21,5.75,4.88,
6.21,8.33,4.34,2.07,1.16,0.63,0.41,1.20,3.11,4.21))
ggplot(df,aes(x=month,y=US)) +
geom_line(col='deepskyblue4')+
geom_line(aes(y=df[,'lim']))+
theme_bw()
This is the original plot (in black the variable threshold)
And this is what I am attempting to get with geom_ribbon
, however I do not know how to do it:
Suggestions would be greatly appreciated.
Thank you.
Upvotes: 0
Views: 492
Reputation: 9933
You can use geom_ribbon
, but first you need to process the data a little.
library(tidyverse)
#set US to lim if lim > US
df2 <- df %>%
mutate(US = if_else(lim > US, US, lim))
ggplot(df,aes(x=month,y=US)) +
geom_ribbon(data = df2, aes(x = month, ymin = US, ymax = lim), fill = "pink") +
geom_line(col='deepskyblue4')+
geom_line(aes(y=lim))+
labs(title=paste('Station',sep=' '),x="Nº months", y = "Hm3",size=2)+
theme_bw()
Upvotes: 1
Reputation: 2101
You can use geom_ribbon
, if you set one of ymin
or ymax
to NA
for those x
-values you don't want to be filled:
ggplot(df, aes(x = month,
ymin = ifelse(lim>US, lim, NA),
ymax = US,
y = US)) +
geom_ribbon(fill = "pink") +
geom_line(color = "deepskyblue4")+
geom_line(aes(y = lim))+
theme_bw()
Edit: If you want to fill the gaps, you could interpolate the data for a nicer plot:
df_itpl <- data.frame(month = seq(min(df$month), max(df$month), .1))
df_itpl$US <- approx(x = df$month, y = df$US, xout = df_itpl$month)$y
df_itpl$lim <- approx(x = df$month, y = df$lim, xout = df_itpl$month)$y
ggplot(df_itpl, aes(x = month,
ymin = ifelse(lim>US, lim, NA),
ymax = US,
y = US)) +
geom_ribbon(fill = "pink") +
geom_line(color = "deepskyblue4")+
geom_line(aes(y = lim))+
theme_bw()
Upvotes: 1