2017-02-14 108 views
11

我試圖用ggplot2生成多個網格地塊。所以,我想生成具有以下x軸的附加箱線分佈圖,並且針對不同人羣和變量這樣的:ggplot2 - 多個地塊縮放

Example

CODE:我想這樣做與下面的代碼:

library(ggplot2) 
require(grid) 

x=rbind(data.frame(D1=rnorm(1000),Name="titi",ID=c(1:1000)), 
    data.frame(D1=rnorm(1000)+1,Name="toto",ID=c(1:1000))) 

space=1 
suite=1 
p1=ggplot(x, aes(x=D1, color=Name, fill=Name)) + 
geom_histogram(aes(y=..density..),alpha=0.35,color=adjustcolor("white",0),position="identity",binwidth = 0.05)+ 
    geom_density(alpha=.2,size=1)+ 
    theme_minimal()+ 
    labs(x=NULL,y="Density")+ 
    theme(legend.position = "top", 
     legend.title = element_blank())+ 
    scale_fill_manual(values=c("gray30","royalblue1"))+ 
    scale_color_manual(values=c("gray30","royalblue1")) 

p2=ggplot(x, aes(x=factor(Name), y=D1,fill=factor(Name),color=factor(Name)))+ 
    geom_boxplot(alpha=0.2)+ 
    theme_minimal()+ 
    coord_flip()+ 
    labs(x=NULL,y=NULL)+ 
    theme(legend.position = "none", 
     axis.text.y = element_blank(), 
     axis.text.x = element_blank(), 
     panel.grid.minor.x = element_blank(), 
     panel.grid.major.x = element_blank(), 
     panel.grid.minor.y = element_blank(), 
     panel.grid.major.y = element_blank())+ 
    scale_fill_manual(values=c("gray30","royalblue1"))+ 
    scale_color_manual(values=c("gray30","royalblue1")) 

grid.newpage() 
pushViewport(viewport(layout=grid.layout(5,1))) 
define_region <- function(row, col){ 
    viewport(layout.pos.row = row, layout.pos.col = col) 
} 
print(p1, vp=define_region(1:4,1)) 
print(p2, vp=define_region(5,1)) 

結果:

enter image description here

問題:在我的搜索過程中,我觀察到密度分佈圖與盒圖之間的比例不一樣(問題1)。我還沒有找到解決方案來繪製這兩個網格圖(我迷路了)。

+0

@Henrik非常感謝您的選擇。我已經測試過這個解決方案,但我對此沒有信心。 –

+0

添加行'p2 <-p2 +主題(plot.margin =單位(c(0,0.3,0,1.5),「cm」))'將在一個捏中工作。此解決方案可能需要對箱線邊距進行微調。也許如果有人能想出一個設置兩者的方法或使用'p1'邊距並將其應用於'p2'。 – N8TRO

回答

10

隨着cowplot包,這變得更容易一些。但是,我們應該適當地設置x軸範圍以確保它們對於兩個圖都是相同的。這是因爲密度圖自然比純數據圖寬一些,因此p1的座標軸會稍寬。當軸固定時,我們可以排列並對齊它們(軸文本和邊距將不再重要)。

library(cowplot) 
comb <- plot_grid(p1 + xlim(-5, 5), 
        p2 + ylim(-5, 5),    # use ylim for p2 because of coord_flip() 
        align = 'v', rel_heights = c(4, 1), nrow = 2) 

enter image description here

同樣,我們可以安排倍數組合地塊:

plot_grid(comb, comb, comb, comb) 

enter image description here

+0

MAGIC !!!非常感謝@Axeman:D –