I am trying to get a geom_area to have twin colours dependant on value of Y axis.
So for example if we have a geom_area with a max X value of 50, I would like the fill colour to be blue when below 10 and red when above 10.
Sample Data;
df <- data.frame(
y = sample(1:50),
x = sample(1:50)
)
The closest that I have managed to get thus far is by using the following code;
ggplot(data = df, aes(x = x)) +
geom_area(aes(y = y),fill = "red") +
geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue")
This almost gets me what I require however the problem is that the horizontal split is not completely across the geom_area, as when the next value falls below the max value the edge of the ribbon goes straight to the next point, which upsets the split.
This is plotting exactly what the code tells it, so I must be using the wrong method to create the split in colours, but cannot figure out how to do it correctly.
A quick fix would be to interpolate between the x-values using approx
. Set the n
argument (the number of interpolation points) to a high-enough value to get blue all the way across:
ggplot(data = as.data.frame(approx(df,n=1000)), aes(x = x)) +
geom_area(aes(y = y),fill = "red") +
geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue") +
theme_classic()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With