【发布时间】:2011-10-15 07:39:52
【问题描述】:
也许这是一个愚蠢的问题,但我在 ggplot2 的手册和“阿姨”google 中都找不到答案...
如果我有一个中点和一个直径,如何用 ggplot2 作为附加层绘制一个圆? 感谢您的帮助。
【问题讨论】:
-
谷歌阿姨对我的反应更灵敏。 This 可能会有所帮助。
也许这是一个愚蠢的问题,但我在 ggplot2 的手册和“阿姨”google 中都找不到答案...
如果我有一个中点和一个直径,如何用 ggplot2 作为附加层绘制一个圆? 感谢您的帮助。
【问题讨论】:
一个更新、更好的选择利用了一个名为 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))
}
以及它的使用演示:
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()
【讨论】:
grid.circle,但要完成这项工作需要了解grid 系统。
如果目的只是注释一个圆,您可以简单地使用带有几何“路径”的注释。无需创建数据框或函数:
#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)))
【讨论】:
您好,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")
产生:
我希望它能让你开始为你的目的编写自定义示例。
【讨论】:
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)
【讨论】:
为了后代,这里有一个更灵活的圆形解决方案,它使用支持填充、颜色、alpha 和大小的 annotate 和 geom_ribbon。
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)
【讨论】:
也试试这个,
ggplot() + geom_rect(aes(xmin=-1,ymin=-1,xmax=1,ymax=1), fill=NA) + coord_polar()
要点是,某些坐标系中的圆通常不是其他坐标系中的圆,除非您使用 geom_point。您可能希望使用笛卡尔坐标确保纵横比为 1。
【讨论】:
仅出于完整性考虑:thomasp85 的包ggforce 提供geom_circle
【讨论】: