自由缩放,但每个面板的x / y范围相同

时间:2012-08-16 17:10:08

标签: r ggplot2

我尝试使用aspect = 1进行自由缩放,但每个面板中的x / y范围相同。在下面的示例中,这意味着b中的x缩放应该是(-0.04,0.04)。

编辑:添加格子版

library(ggplot2)
d = data.frame(x=rnorm(100),group=c("A","B"))
d$y = d$x+rnorm(100,0,0.5)
d[d$group=="B","x"]=d[d$group=="B","x"]/100
d[d$group=="B","y"]=d[d$group=="B","y"]/60
qplot(x,y,data=d,asp=1) + facet_wrap(~group,scale="free")

require(lattice)
xyplot(y~x|group, data=d,aspect=1,scales=list(relation="free"),
   prepanel=function(x,y){
     lims = c(min(x,y), max(x,y))
     list(xlim=lims,ylim=lims)
   } )

in each panel, the x and y range should be the same

1 个答案:

答案 0 :(得分:6)

由于ggplot2的最新版本在内部使用gtable,您可以非常轻松地执行此类任务:

d = data.frame(x=rnorm(100),group=c("A","B"))
d$y = d$x+rnorm(100,0,0.5)
d[d$group=="B","x"]=d[d$group=="B","x"]/100
d[d$group=="B","y"]=d[d$group=="B","y"]/60

# create plots for each level of group
p <- lapply(levels(d$group), 
  function(i) {
    dat <- subset(d, group == i)
    lim <- range(c(dat$x, dat$y))
    ggplot_gtable(ggplot_build(qplot(x,y,data=dat,asp=1) + 
      facet_wrap(~group,scale="free") + 
      coord_equal() +
      xlim(lim) + ylim(lim)))
    })

# tweaking margins
p[[1]] <- p[[1]][, -6]
p[[2]] <- p[[2]][, -(1:2)]

# draw it
grid.newpage()
grid.draw(cbind(p[[1]], p[[2]], size = "first"))

enter image description here