2013-12-23 106 views
5

我想在點圖中包含一系列同心圓作爲網格。目標是讓觀衆瞭解劇情中的哪些點具有大致相同的幅度。 我創建了一個黑客做到這一點:同心圓像一個網格,以原點爲中心

add_circle_grid <- function(g,ncirc = 10){ 
    gb <- ggplot_build(g) 
    xl <- gb$panel$ranges[[1]]$x.range 
    yl <- gb$panel$ranges[[1]]$y.range 
    rmax = sqrt(max(xl)^2+max(yl)^2) 
    theta=seq(from=0,by=.01,to=2*pi) 
    for(n in 1:ncirc){ 
    r <- n*rmax/ncirc 
    circle <- data.frame(x=r*sin(theta),y=r*cos(theta)) 
    g<- g+geom_path(data=circle,aes(x=x,y=y),alpha=.2) 
    } 
    return(g+xlim(xl)+ylim(yl)) 
} 

xy<-data.frame(x=rnorm(100),y=rnorm(100)) 
ggplot(xy,aes(x,y))+geom_point() 
ggg<-add_circle_grid(ggplot(xy,aes(x,y))+geom_point()) 
print(ggg) 

但我不知道是否有這樣做更ggplot方式。我也考慮過使用極座標,但它不允許我以相同的方式設置x和y極限。 最後,我不介意指示每個圓的半徑的小文本標籤。

編輯 也許這是要求太多,但我還有其他兩件事情。

  1. 軸界限應該保持不變(這可以通過ggplot_build完成)
  2. 可以與面這項工作?據我可以告訴你,如果我想動態地添加圓圈,需要以某種方式找出方面。
+0

看來答案建議有辦法做到這一點:-) 仍然不知道如果有使用極座標的方法。 – dpmcsuss

回答

6

enter image description here

set.seed(1) 
xy <- data.frame(x=rnorm(100),y=rnorm(100)) 
rmax = sqrt(max(xy$x)^2+max(xy$y)^2) 
theta=seq(from=0,by=.01,to=2*pi) 
ncirc=10 

dat.circ = do.call(rbind, 
    lapply(seq_len(ncirc),function(n){ 
    r <- n*rmax/ncirc 
    data.frame(x=r*sin(theta),y=r*cos(theta),r=round(r,2)) 
})) 

rr <- unique(dat.circ$r) 

dat.text=data.frame(x=rr*cos(30),y=rr*sin(30),label=rr) 

library(ggplot2) 

ggplot(xy,aes(x,y))+ 
    geom_point() + 
    geom_path(data=dat.circ,alpha=.2,aes(group=factor(r))) + 
    geom_text(data=dat.text,aes(label=rr),vjust=-1) 
+0

這看起來不錯!謝謝! – dpmcsuss

5

這個怎麼樣用ggplot2grid

require(ggplot2) 
require(grid) 

x<-(runif(100)-0.5)*4 
y<-(runif(100)-0.5)*4 

circ_rads<-seq(0.25,2,0.25) 

qplot(x,y)+ 
    lapply(circ_rads,FUN=function(x)annotation_custom(circleGrob(gp=gpar(fill="transparent",color="black")),-x,x,-x,x))+ 
    geom_text(aes(x=0,y=circ_rads+0.1,label=circ_rads)) + coord_fixed(ratio = 1) 

enter image description here

+0

我也喜歡。 – dpmcsuss

+2

請注意,繪製的圓形實際上並不是數據空間的圓形。 X方向的半徑是1.5單位,但在Y方向是2.0單位。將'+ coord_fixed(ratio = 1)'添加到繪圖命令可能會很有用。 – bdemarest

+0

好點,並予以糾正 – Troy