Dom*_*nik 55 geometry r ggplot2
也许这是一个愚蠢的问题,但我找不到ggplot2手册中的答案,也没有找到"阿姨"谷歌......
如果我有一个中点和一个直径,如何用ggplot2绘制一个圆作为附加图层?谢谢你的帮助.
jor*_*ran 68
更新,更好的选项利用名为ggforce的扩展包来定义明确性geom_circle.
但为了后人的缘故,这是一个简单的圆形函数:
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))
}
Run Code Online (Sandbox Code Playgroud)
并演示它的用途:
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()
Run Code Online (Sandbox Code Playgroud)

bap*_*ste 13
和ggplot2 >= 0.9你一起也可以
library(grid)
qplot(1:10, 1:10, geom="blank") +
annotation_custom(grob=circleGrob(r=unit(1,"npc")), xmin=2, xmax=4, ymin=4, ymax=6)
Run Code Online (Sandbox Code Playgroud)
Lui*_*uis 13
如果目的仅用于注释圆,则可以简单地使用带几何"路径"的注释.无需创建数据框或功能:
#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)))
Run Code Online (Sandbox Code Playgroud)
嗨以下代码来自ggplot2 Google群组可能很有用:
dat = data.frame(x=runif(1), y=runif(1))
ggplot() + scale_x_continuous(limits = c(0,1)) +
scale_y_continuous(limits = c(0,1))+
geom_point(aes(x=x, y=y), data=dat, size=50, shape=1, color="gold4")
Run Code Online (Sandbox Code Playgroud)
哪个产生:

我希望它能让你开始为你的目的破解自定义示例.
也试试这个,
ggplot() + geom_rect(aes(xmin=-1,ymin=-1,xmax=1,ymax=1), fill=NA) + coord_polar()
Run Code Online (Sandbox Code Playgroud)
要点是,某些坐标系中的圆通常在其他坐标系中不是圆,除非您使用 geom_point。您可能希望确保笛卡尔坐标的纵横比为 1。
为了后人的缘故,这里有一个更灵活的圆形解决方案,使用annotate和geom_ribbon,支持填充,颜色,alpha和大小.
gg_circle <- function(r, xc, yc, color="black", fill=NA, ...) {
x <- xc + r*cos(seq(0, pi, length.out=100))
ymax <- yc + r*sin(seq(0, pi, length.out=100))
ymin <- yc + r*sin(seq(0, -pi, length.out=100))
annotate("ribbon", x=x, ymin=ymin, ymax=ymax, color=color, fill=fill, ...)
}
square <- ggplot(data.frame(x=0:1, y=0:1), aes(x=x, y=y))
square + gg_circle(r=0.25, xc=0.5, yc=0.5)
square + gg_circle(r=0.25, xc=0.5, yc=0.5, color="blue", fill="red", alpha=0.2)
Run Code Online (Sandbox Code Playgroud)