R 用ggplot2画一个圆

R 用ggplot2画一个圆,r,ggplot2,geometry,R,Ggplot2,Geometry,也许这是一个愚蠢的问题,但我在ggplot2手册和“阿姨”谷歌上都找不到答案 如果我有一个中点和一个直径,如何用ggplot2作为附加层绘制一个圆? 感谢您的帮助。您好,小组中的以下代码可能有用: 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)

也许这是一个愚蠢的问题,但我在ggplot2手册和“阿姨”谷歌上都找不到答案

如果我有一个中点和一个直径,如何用ggplot2作为附加层绘制一个圆?
感谢您的帮助。

您好,小组中的以下代码可能有用:

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")
产生:


我希望它能让您开始为自己的目的编写自定义示例。

一个更新、更好的选项利用了一个名为的扩展包,该扩展包定义了一个明确的
geom\u圆

但为了子孙后代,这里有一个简单的圆函数:

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))
}
#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)))
circleFun也试试这个

 ggplot() + geom_rect(aes(xmin=-1,ymin=-1,xmax=1,ymax=1), fill=NA) + coord_polar()

点是,某些坐标系中的圆通常不是其他坐标系中的圆,除非您使用geom_点。您可能希望使用笛卡尔坐标确保纵横比为1。

使用
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)

如果仅用于注释圆,则可以简单地使用带有几何图形“路径”的注释。无需创建数据帧或函数:

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))
}
#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)))
#g是你的情节
#r、 xc,yc是半径和中心坐标

g为了子孙后代,这里有一个更灵活的圆解决方案,使用注释和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)

gg_circle只是为了完整性:thomasp85提供的套装
ggforce
提供了
geom_circle

谷歌阿姨对我的反应更积极。可能会有所帮助。我可能错了,但我认为这种方法不能解决OP的问题,即如何在给定圆心和直径的情况下绘制圆。这将是非常困难的,以获得正确的直径使用大小美学。是的,我同意,这只是一个指针在正确的方向不是一个完整的解决方案。谢谢你的提示Neo_我,但Joran张贴的方式更适合我的需要。很高兴看到这一点,这是我正在寻找的。谢谢Hanks Joran这就是我要找的。。。我只是想知道,你必须使用函数才能在ggplot中实现这一点。如果我没记错的话,plot有一个内置函数。但是这个情节看起来更美好;-)@多米尼克-确实存在
grid.circle
,但要实现这一点,需要对
grid
系统有一些了解。我想要绘制的是散点图上的重要地平线。对于这一点,jorans的解决方案似乎是最好的方法。但也非常感谢您的提示。这会随着画布的大小而改变大小。