同心圆像网格,以原点为中心

dpm*_*uss 6 r ggplot2

我想在一个点图中包含一系列同心圆作为网格.目标是让观察者知道图中哪些点具有大致相同的幅度.我创建了一个hack来做到这一点:

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)
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更多的ggplot方法来做到这一点.我也考虑使用极坐标,但它不允许我以相同的方式设置x和y限制.最后,我不介意指示每个圆的半径的小文本标签.

编辑 也许这是要求太多,但我还想要另外两件事.

  1. 轴限应该保持不变(可以通过ggplot_build完成)
  2. 这可以与facets一起使用吗?据我所知,如果我想动态添加圆圈,我需要以某种方式找出方面.

ags*_*udy 7

在此输入图像描述

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)
Run Code Online (Sandbox Code Playgroud)


Tro*_*roy 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) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 请注意,绘制的圆圈实际上并不是关于数据空间的圆圈.x方向的半径为1.5个单位,但在y方向的半径为2.0个单位.在绘图命令中添加`+ coord_fixed(ratio = 1)`可能很有用. (2认同)