Tanggal :September 28, 2020

R36. Drawing Polygons in R

Spread the love

To draw polygons, we have to give vertices as we loop over the polygon counterclockwise.

We use a curve with roots of -1,0,+1. We divide the x-axis based on these roots (will become 4 shaded regions).

We make loops in x.1, x.2, x.3 and x.4, the four divisions of x that we chose. For x.2 and x.3, we do not have to complete the loop as the default is that the polygon will be closed.


# ex36.R

y <- function(x) {
x^3 - x
}
x <- seq(-1.5, 1.5, .01)
x.1 <- x[x >= -1.5 & x <= -1]
x.2 <- x[x >= -1 & x <= 0]
x.3 <- x[x >= 0 & x <= 1]
x.4 <- x[x >= 1 & x <= 1.5]
plot(x,y(x), type = 'l', col = 'blue', xlim = c(-1.5,1.5))
abline(h = 0, col = 'magenta')
polygon(c(x.1,rev(x.1)),
c(y(x.1),rep(0,length(x.1))), col = 'violet')
polygon(c(x.2), c(y(x.2)), col='green')
polygon(c(x.3), c(y(x.3)), col='red')
polygon(c(x.4,rev(x.4)),
c(rep(0,length(x.4)),y(rev(x.4))), col='yellow')
title(expression('y = x'^3*'-x'))

Output:

Share

Leave a Reply

Your email address will not be published. Required fields are marked *