0

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?

00koeffers
  • 327
  • 2
  • 11
  • What's wrong with the answer to that question? It looks like the answer is simply to be sure to sort your input data by `x` (i.e., replace `x` with `x[order(x)]` and `y` with `y[order(y)]`). Please provide an [MRE](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example-aka-mcve-minimal-complete-and-ver) if this is not the case. – MichaelChirico Nov 28 '17 at 09:22
  • There is nothing wrong with the answer. I just wanted to point out that i've read this answer and that I understood it in a way that brings me to my idea for a solution. It wasn't meant as a critic, but rather as an explanation. If I use `order()`, the data gets ordered with increasing values (what is not what I want on a y-axis). I am not able to make an reproducable example unfortunately, since I can not upload my dataset and could not reproduce it with random values... – 00koeffers Nov 28 '17 at 13:44
  • sorry, I made a typo. `y[order(x)]` – MichaelChirico Nov 28 '17 at 13:47

1 Answers1

2

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

Johannes Ranke
  • 469
  • 3
  • 11