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.
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.
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()
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With