showkey
showkey

Reputation: 298

Why is there a slim gap in polygon function?

There is a slim gap in the graph after you run the code.

x = seq(0, 1, by=0.01)
y1=x
y2=x^2
plot(x, y1,type="l")
lines(x,y2,type="l",col="red")
xx1<-c(0,x[x<1  & x>0 ],1,x[x<1  & x>0 ],0)
yy1<-c(0,x[x<1  & x>0 ],1,(x[x<1  & x>0 ])^2,0)
polygon(xx1,yy1,col="yellow")

Please see the attachment,why is there a slim gap?how can i delete it,let it be filled by yellow colour ? enter image description here

Upvotes: 3

Views: 78

Answers (1)

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32391

The cause of the problem is easier to see if you reduce the number of points:

x <- seq(0, 1, by=0.2)
plot(  x, x,   type="l" )
lines( x, x^2, col="red" )
xx1 <- c(0,x[x<1  & x>0 ],1,x[x<1  & x>0 ],0)
yy1 <- c(0,x[x<1  & x>0 ],1,x[x<1  & x>0 ]^2,0)
polygon(xx1, yy1, lwd=3, col="wheat")
points(xx1, yy1)

enter image description here

The points are correct, but the order is not. For a convex polygon, xx1 should be first increasing, then decreasing.

plot(  x, x,   type="l" )
lines( x, x^2, col="red" )
xx1 <- c(x, rev(x))
yy1 <- c(x, rev(x)^2)
polygon(xx1, yy1, lwd=3, col="wheat")

Upvotes: 5

Related Questions