Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free scale, but same per-panel range in x/y

Tags:

r

ggplot2

I try to get free scaling with aspect=1, but same range in x/y in each panel. In the example below, this means that x-scaling in b should be (-0.04,0.04).

Edited: added lattice version

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

like image 730
Dieter Menne Avatar asked Aug 16 '12 17:08

Dieter Menne


1 Answers

As the latest version of ggplot2 uses gtable internally, you can do this kind of task quite easily:

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

like image 141
kohske Avatar answered Nov 03 '22 07:11

kohske