00koeffers
00koeffers

Reputation: 327

R: Fill area under curve with Polygon()

Is there an universal way to fill the area under a curve with the polygon() function?

As far as I understand the answer in this post: Fill under line curve I would assume that polygon(c(min(x), x, max(x)), c(min(y), y, min(y)) will always work, because it starts on the bottom left, goes up to the curve, down to the button right and then back to the beginning.

But it does not always work. Sometimes, I still get a graph like in this question: Why polygon in R works with a full curve but not with a half curve? where R simply draws a line and fills in under and above it.

So what would be an iput (or an other function) that will always work?

Upvotes: 1

Views: 3812

Answers (1)

Johannes Ranke
Johannes Ranke

Reputation: 469

Maybe you need na.rm = TRUE for min(y)? Anyways, here is a function giving you the possibility to specify a horizontal border to which to fill:

fill_to_border <- function(f, from, to, y_border = 0, col = 1) {
  curve_points <- curve(f, from, to) 
  polygon_x <- c(min(curve_points$x), curve_points$x, max(curve_points$x))
  polygon_y <- c(y_border, curve_points$y, y_border)
  polygon_points <- list(x = polygon_x, y = polygon_y)
  polygon(polygon_points, col = col)
}

fill_to_border(dnorm, -4, 0)

enter image description here

Upvotes: 2

Related Questions