簡體   English   中英

用ggplot2畫一個圓圈

[英]Draw a circle with ggplot2

也許這是一個愚蠢的問題,但我找不到ggplot2手冊中的答案,也沒有找到“阿姨”谷歌......

如果我有一個中點和一個直徑,如何用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()

在此輸入圖像描述

如果目的僅用於注釋圓,則可以簡單地使用帶幾何“路徑”的注釋。 無需創建數據框或功能:

#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 >= 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)

嗨以下代碼來自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")

哪個產生: 在此輸入圖像描述

我希望它能讓你開始為你的目的破解自定義示例。

為了后人的緣故,這里有一個更靈活的圓形解決方案,使用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且具有笛卡爾坐標。

只是為了完整性:包ggforce通過thomasp85提供geom_circle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM