2014-06-20 31 views
15

問題在ggplot對準地塊的危險

如何結合不同的地塊(GGPLOT2),具有不同的y軸和不同情節的高度,但仍保留對齊?

DETAIL

當組合與grid.arrange(方法1)圖,其中的不同的y軸單位,它們不對齊。一種解決方法是使用gtable(method2),但我無法調整圖的相對高度。

require(ggplot2) 

#Make two plots, with different y axis 
    x = c(1, 5) 
    y= c(.1, .4) 
    data1<-data.frame(x,y) 
    top<- 
    ggplot(data1, aes(x=x, y=y))+ 
    geom_line() 

    x = c(1, 5) 
    y= c(100000, 400000) 
    data2<-data.frame(x,y) 
    bottom<- 
    ggplot(data2, aes(x=x, y=y))+ 
    geom_line() 


# Method 1 - Grid Extra 
    require(gridExtra) 
    grid.arrange(top, bottom, heights=c(.6,.3)) 

方法1周的結果在該圖中,這是不對準是由於不同長度的y軸的標籤:

enter image description here

#Method 2 - gtable 
    require(gtable) 
    #Extract Grobs 
    g1<-ggplotGrob(top) 
    g2<-ggplotGrob(bottom) 
    #Bind the tables 
    g<-gtable:::rbind_gtable(g1, g2, "first") 
    #Remove a row between the plots 
    g <- gtable_add_rows(g, unit(-1,"cm"), pos=nrow(g1)) 
    #draw 
    grid.newpage() 
    grid.draw(g) 

方法2周的結果在對齊情節,但我無法調整每個情節的高度。 enter image description here

謝謝!

+1

[**這可能會幫助**](http://stackoverflow.com/a/16368413/1478381) –

回答

17

在你gtable g,你可以設置相對面板的高度,

require(gtable) 
g1<-ggplotGrob(top) 
g2<-ggplotGrob(bottom) 
g<-gtable:::rbind_gtable(g1, g2, "first") 
panels <- g$layout$t[grep("panel", g$layout$name)] 
g$heights[panels] <- unit(c(1,2), "null") 

grid.newpage() 
grid.draw(g) 
+0

工程完美無瑕,並且比grid.arrange方法更好的結果。謝謝。 – wab

+0

感謝您的好評!但是,在網格更新中可能會有所改變,但是現在(版本3.3.0)爲此工作的第二行必須是:'g $ heights [panels] < - unit(c(2,1),「null」)' –

+0

@RNoob正確,在grid和ggplot2中,這個級別的東西都發生了變化 – baptiste