1

I'd like to color the triangular region here under the line that you see so I pass in the vector of x coordinates and y coordinates BUT the region is not shading in.

can you get the region under the line shaded red? the bottom of the region is the x axis and the top is the line. Thank you.

Here is the code:

  x = c(0,1)
   y = c(1,2)
   x
   y
   plot(x,y)
   polygon(x, y, col="red")
user3022875
  • 8,598
  • 26
  • 103
  • 167
  • 1
    you pass only two x,y coordinates to polygon, so it will only shade the "area" enclosed within what is effectively a straight line - which has no area to shade. See http://stackoverflow.com/questions/3494593/shading-a-kernel-density-plot-between-two-points for explanation of how to shade under a curve – dww May 09 '16 at 01:42
  • Possible duplicate of [Shading a kernel density plot between two points.](http://stackoverflow.com/questions/3494593/shading-a-kernel-density-plot-between-two-points) – dww May 09 '16 at 01:44

1 Answers1

0

A triangle has three points. Your x and y vectors only describe two points.

The polygon() function can draw any triangle or higher-order polygon, but you have to fully define the polygon by passing all of its vertices in the x and y arguments.

We can solve the problem by supplementing the x and y vectors with an additional element that fills in the missing vertex when passing these vectors to the polygon() function.

Since you've indicated you want to shade the area under the line, here's how I would do this:

  • First I'll address the additional y coordinate, since it's easier. We simply need to use the minimum of the known y coordinates, for which we can use min().
  • For x, we need to copy the x coordinate that corresponds to the vertex with the higher y-coordinate, for which we can use which.max() on y and then subscripting x.

x <- c(0,1);
y <- c(1,2);
plot(x,y);
polygon(c(x,x[which.max(y)]),c(y,min(y)),col='red');

plot

bgoldst
  • 34,190
  • 6
  • 38
  • 64