Draw a circle with ggplot2

Dominik picture Dominik · Jul 28, 2011 · Viewed 43.1k times · Source

Maybe it is a silly question, but I couldn't find the answer in the handbook of ggplot2 nor with "aunt" google...

How do I plot a circle with ggplot2 as an additional layer if I have a middle point and a diameter? Thanks for your help.

Answer

joran picture joran · Jul 28, 2011

A newer, better option leverages an extension package called ggforce that defines an explicity geom_circle.

But for posterity's sake, here's a simple circle function:

circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){
    r = diameter / 2
    tt <- seq(0,2*pi,length.out = npoints)
    xx <- center[1] + r * cos(tt)
    yy <- center[2] + r * sin(tt)
    return(data.frame(x = xx, y = yy))
}

And a demonstration of it's use:

dat <- circleFun(c(1,-1),2.3,npoints = 100)
#geom_path will do open circles, geom_polygon will do filled circles
ggplot(dat,aes(x,y)) + geom_path()

enter image description here