Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a circle with ggplot2

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.

like image 994
Dominik Avatar asked Jul 28 '11 16:07

Dominik


People also ask

How do I draw a circle in R?

There is no direct function in R to draw a circle but we can make use of plotrix package for this purpose. The plotrix package has a function called draw. cirlce which is can be used to draw a circle but we first need to draw a plot in base R then pass the correct arguments in draw. circle.


2 Answers

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

like image 153
joran Avatar answered Oct 07 '22 08:10

joran


If the purpose is only to annotate a circle, you can simply use annotate with geometry "path". No need to create a data frame or function:

#g is your plot #r, xc, yc are the radius and center coordinates  g<-g+annotate("path",    x=xc+r*cos(seq(0,2*pi,length.out=100)),    y=yc+r*sin(seq(0,2*pi,length.out=100))) 
like image 22
Luis Avatar answered Oct 07 '22 10:10

Luis