也许这是一个愚蠢的问题,但我找不到ggplot2手册中的答案,也没有找到“阿姨”谷歌......
如果我有一个中点和一个直径,如何用ggplot2绘制一个圆作为附加图层?谢谢你的帮助 .
与 ggplot2 >= 0.9 你也可以
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)
如果目的仅用于注释圆,则可以简单地使用带几何“路径”的注释 . 无需创建数据框或功能:
#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")
哪个产生:
我希望它能让你开始为你的目的破解自定义示例 .
更新,更好的选项利用名为ggforce的扩展包来定义明确的 geom_circle .
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()
为了后人的缘故,这里有一个更灵活的圆形解决方案,使用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)
试试这个,
ggplot() + geom_rect(aes(xmin=-1,ymin=-1,xmax=1,ymax=1), fill=NA) + coord_polar()
关键是,除非使用geom_point,否则某些坐标系中的圆圈通常不是其他圆圈 . 您可能希望确保宽高比为1且具有笛卡尔坐标 .
只是为了完整性:由thomasp85提供的包 ggforce 提供 geom_circle
ggforce
7 回答
与
ggplot2 >= 0.9
你也可以如果目的仅用于注释圆,则可以简单地使用带几何“路径”的注释 . 无需创建数据框或功能:
您好ggplot2 Google组的以下代码可能很有用:
哪个产生:
我希望它能让你开始为你的目的破解自定义示例 .
更新,更好的选项利用名为ggforce的扩展包来定义明确的
geom_circle
.但为了后人的缘故,这是一个简单的圆形函数:
并演示它的用途:
为了后人的缘故,这里有一个更灵活的圆形解决方案,使用annotate和geom_ribbon,支持填充,颜色,alpha和大小 .
试试这个,
关键是,除非使用geom_point,否则某些坐标系中的圆圈通常不是其他圆圈 . 您可能希望确保宽高比为1且具有笛卡尔坐标 .
只是为了完整性:由thomasp85提供的包
ggforce
提供geom_circle