I'm trying to fill the area between a line and 0 but this doesn't work as the fill area "overflows" the line:
library(ggplot2)
# Create some dummy data
x <- c(1, 2, 3, 4, 5)
y <- c(1, -2, 3, -4, 5)
# Create a data frame with the x and y values
df <- data.frame(x, y)
# Create the line chart
ggplot(df, aes(x, y)) +
geom_line() +
# Fill the area above the line with a semi-transparent red color
# when y is more than 0
geom_ribbon(data=df, aes(ymin=0, ymax=ifelse(y >= 0, y, 0)), fill = "red", alpha=0.5)
Any ideas on how to make this work?
This solution creates a helper dataframe with added rows for every point the line crosses the x axis. Including these points in your ribbon will make it align correctly with the line.