2012-08-16 48 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