2012-08-16 47 views
10

我嘗試使用aspect = 1進行自由縮放,但每個面板的x/y範圍相同。在下面的例子中,這意味着b中的x縮放應該是(-0.04,0.04)。自由標度,但每個面板的x/y範圍相同

編輯:增加了點陣版

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

+1好問題。我擺弄着周圍,但無法按你的要求工作。 – Andrie 2012-08-16 18:12:02

+4

@Andrie:作爲一位死於羊毛的格鬥家,我首先想到的只是我的無知而已。在您發表評論後,我發現了一個線索[https://groups.google.com/forum/?fromgroups#!topic/ggplot2/cDzL_yHew0I[1-25]],表明在ggplot2中這不是那麼容易。 – 2012-08-16 18:30:37

+0

看起來像我錯過了負面的一個:http://stackoverflow.com/questions/7905828/multi-panel-plots-in-ggplot2-scales-that-are-free-and-equal?rq=1 – 2012-08-16 19:00:39

回答

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

+0

謝謝@kohske,但使用預處理的晶格解決方案似乎對我來說更加精簡。 – 2012-09-30 14:44:40

+0

+1,儘管我不得不同意迪特的觀點,但ggplot的實力通常是不需要低級細節的事實。 – 2012-09-30 15:05:15