I'd like to make a line plot where I need to clip some lines below/above certain y values. As an example
x <- c(1,2,3,4,5,6,7,8,9,10)
y1 <- c(1,2,3,4,5,6,7,8,9,10)
y2 <- c(2,4,6,8,10,12,14,16,18,20)
df <- data_frame(x, y1, y2)
#make plot for df
ggplot(data=df, aes(x=x, group=1)) +
#plot y=x
geom_line(data=df, aes(x=x, y=y1, colour="red"))+
#plot y=2x for values of y equal to/ above 3
geom_line(data=df, aes(x=x, y=y2 >=3, colour="blue"))
obviously this doesn't work but is it possible? And if so, how? The obvious solution would be to edit the data frame itself but for my final goal this won't work. Another solution would be to make the plot invisible (in this case) above y=3 but was unsure if thats possible either
Apologies if it's been asked before. I tried searching around but didn't find anything. Many thanks,
A possible solution is to make a factor of your condition and use that to color the line:
ggplot(data=df, aes(x=x, y=y2, group=1)) +
geom_line(aes(color = factor(y2 >= 3)))
which gives:
Upon re-reading your question, I think I might have misinterpreted it. Slightly adapting your code to only include the values equal to or above 3:
ggplot(data=df, aes(x=x, y=y1)) +
geom_line(colour="red")+
geom_line(data=df[df$y2 >= 3,], aes(x=x, y=y2), colour="blue")
which gives: