Home > front end >  Fill area bellow geom_curve in ggplot
Fill area bellow geom_curve in ggplot

Time:10-20

This is my code:

ggplot(data = tibble(x = 1:20, y = 1:20),
       aes(x = x, y = y))   
  
  geom_curve(x = 10, y = 7.55, xend = 15, yend = 7.6,
             curvature = .28, size = .7250, color  ='black') 
  
  geom_point()

How can I fill the area bellow this curve? Between x = 10 and x = 12 and considering the ymax being the curve.

CodePudding user response:

I don't know how to extract geom_curve's internal data produced during rendering, but here's a method:

gg <- ggplot(data = tibble(x = 1:20, y = 1:20),
       aes(x = x, y = y))   
  geom_curve(x = 10, y = 7.55, xend = 15, yend = 7.6,
             curvature = .28, size = .7250, color  ='black') 
  geom_point()

We'll produce a curve on our own. I'm using 51 here just to get many points; you may want fewer or more depending on the size of your curve and the resolution of your eventual plot.

curvedat <- data.frame(x = seq(10, 15, len = 51))
curvedat$y <- with(curvedat, 4   5*abs((x - 10) / 5 - 0.5)^2)
gg   geom_path(data = curvedat)

ggplot with second curve, for testing/validation

(The two curves are shown together here in order to demonstrate their similarity. There's no assumption of maintaining the original curve in the plot. Also, the second curve is shown offset down, I'm assuming you would address that in your suitability decision.)

Once you have a curve that looks okay, then wrap two "low" points around it and add as a polygon:

gg  
  geom_polygon(data = rbind(
    data.frame(x = min(curvedat$x), y = -Inf),
    curvedat,
    data.frame(x = max(curvedat$x), y = -Inf)
  ))

ggplot2 with curve converted to a polygon

  • Related