Kiefer
Kiefer

Reputation: 163

How do I draw a "donut" polygon in R?

I found a somewhat similar question, but not the same as I'm trying to do I believe. I'm trying to draw a circle with a hole in the middle in R.

I know how to draw a circle using the sampSurf library:

radius = 20
sp.dbh = spCircle(radius, centerPoint=c(x=30,y=80), spID='tree.1') 
plot(sp.dbh$spCircle)

But I would like to draw an "outer ring" with a hole in the middle around this circle. Is there a way to do that? To be clear, the outer edge of the circle should be the inner edge of the ring. Thanks for any help!

Upvotes: 0

Views: 840

Answers (1)

MrFlick
MrFlick

Reputation: 206546

This is kind of ugly, but you could easily write your own function using base graphics function to draw such a shape. We basically just draw the shape in two (slightly overlapping) parts.

ring <- function(x,y,outer,inner, border=NULL, col=NA, lty=par("lty"), N=100, ...) {
    t <- seq(0, pi, length.out=N)
    tx <- seq(0-pi/10, pi+pi/10, length.out=N)
    top <- cbind(c(x+cos(tx)*outer, x-cos(tx)*inner), c(y+sin(tx)*outer, y+sin(tx)*inner))
    bot <- cbind(c(x-cos(tx)*outer, x+cos(tx)*inner), c(y-sin(tx)*outer, y-sin(tx)*inner))
    out <- cbind(c(x+cos(t)*outer,x-cos(t)*outer),  c(y+sin(t)*outer, y-sin(t)*outer))
    inn <- cbind(c(x-cos(t)*inner, x+cos(t)*inner), c(y+sin(t)*inner,  y-sin(t)*inner))
    if (!is.na(col)) {
        polygon(top, border=NA, col = col, ...)
        polygon(bot, border=NA, col = col, ...)
    }
    if(!is.null(border)) {
        lines(out, col=border, lty=lty)
        lines(inn, col=border, lty=lty)
    } else {
        lines(out, lty=lty)
        lines(inn, lty=lty)     
    }
}

#test
plot(0,0, xlim=c(-10,10), ylim=c(-10,10),type="n", asp=1)
ring(1,4,5,2)

enter image description here

Upvotes: 1

Related Questions