Concentric Circles like a grid, centered at origin

百般思念 提交于 2019-11-30 04:48:13

问题


I would like to include a sequence of concentric circles as a grid in a plot of points. The goal is to give the viewer an idea of which points in the plot have approximately the same magnitude. I created a hack to do this:

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)

But I was wondering if there is a more ggplot way to do this. I also considered using polar coordinates but it does not allow me to set x- and y-limits in the same way. Finally, I wouldn't mind little text labels indicating the radius of each circle.

EDIT Perhaps this is asking too much but there are two other things that I would like.

  1. The axis limits should stay the same (which can be done via ggplot_build)
  2. Can this work with facets? As far as I can tell you would need to somehow figure out the facets if I want to add the circles dynamically.

回答1:


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)



回答2:


How about this with ggplot2 and grid:

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) 



来源:https://stackoverflow.com/questions/20736330/concentric-circles-like-a-grid-centered-at-origin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!