I want to create a line plot where everything above the line x = 0 is colored green and everything below the line is colored red. The code I have come up with below is close to the desired behavior, but since geom_line forms discrete connections between the points instead of being a continuous function, the "y > 0" statement is only evaluated at each point in the vector x, and the color is applied to the next part of the line segment.
This creates a weird-looking plot when y is greater than 0 for one x-value, but below 0 for the next x-value. Instead of the colors "smoothly" switching from green to red immediately when the line crosses the x-axis, the line keeps its current color until reaching the next value of x. In the output below, this is very apparent in the red and green lines jumping across the axis instead of smoothly changing color at y = 0.
How can I rewrite this code so that the color aesthetic of my plot is always green for all values y > 0 and red for all values y <= 0, and eliminate the jumping behavior?
Reprex:
library(tidyverse)
library(zoo)
set.seed(4133)
x = seq(1,100)
y = rnorm(100) %>%
rollmean(.,k = 5,na.pad = T,fill = 0)
data = data.frame(x,y)
ggplot(data,aes(x = x, y = y)) +
geom_line(color = ifelse(y > 0,"darkgreen","red")) +
geom_hline(yintercept = 0)
Created on 2022-07-11 by the reprex package (v2.0.1)