简体   繁体   中英

r geom polygon coordinates

What is the correct way to enter coordinates with geom_polygon?

In this plot I would like to draw 2 rectangles.

One going from .5 to 1.5 on the x axis and 148 to 161 on the y axis.

The other going from 1.5 to 2.5 on the x axis and 339 to 352 on the y axis.

The coordinates in the polygon() below work but I'd like to confirm how the coordinates must be entered. Below the coordinates are entered with the bottom line of each rectangle first 148 148 339 339 are entered and then the top line of each rectangle are entered: 161 161 352 352. Is that how the coordinates must be entered - bottom line first then top line?

plot(1, type="n", main="test",
     xlim=c(0, 5), xlab="y",
     ylim=c(0, max( 0,400   )    ), ylab="")

polygon(
x=c(0.5 ,1.5, 1.5, 2.5, 2.5, 1.5, 1.5, 0.5),
y= c(148, 148, 339, 339, 352, 352, 161, 161),
col = "blue", border = NA)

When I enter all 4 coordinates for each rectangle for the first rectangle first and then all 4 coordinates for the second rectangle the plot is wrong:

plot(1, type="n", main="test",
     xlim=c(0, 5), xlab="y",
     ylim=c(0, max( 0,400   )    ), ylab="")

polygon(  x=c(.5,1.5,.5,1.5,1.5,2.5,1.5,2.5 ), y=c(148,148,161,161,339,339,352,352   ),
          col = "red", border = NA)

Thank you.

This is a base plot question rather than ggplot2

polygon is trying to to draw a single polygon rather than the two you want. It is also assuming that the points are in order, and that the last point is connected to the first point

So your second example might work better if you separated the rectangles and reordered the points, perhaps trying

plot(1, type="n", main="test",
     xlim=c(0, 5), xlab="y",
     ylim=c(0, max(0, 400)), ylab="")

polygon(x=c(0.5, 1.5, 1.5, 0.5), y=c(148, 148, 161, 161),
        col = "red", border = NA)
polygon(x=c(1.5, 2.5, 2.5, 1.5), y=c(339, 339, 352, 352),
        col = "red", border = NA)

so rather than

在此处输入图片说明

you would get

在此处输入图片说明

which is what I assume you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM