2016-07-26 70 views
2

我正在做貝葉斯建模,並且我有8個變量,每個變量都有一個相關參數,每對變量都有一個相關參數。所有這些參數都有其後驗密度圖。我想安排在一個上三角形佈局的情節,我使用的結果從 Upper triangle layout多個圖作爲上三角矩陣佈局並格式化爲散點圖

但是,它會更好,如果我能標題/以同樣的方式作爲什麼散點圖做,即標註地塊,我將只在頂部和右邊的標題(變量名),並通過檢查頂部和各分圖的右邊對應的標題,人們就會知道是什麼的相關參數是一個代表。

這裏是我已經實現,在這裏我只用3個變量用於說明最小的例子。

require(ggplot2) 
corr_1 = rnorm(100) 
corr_2 = rnorm(100) 
corr_12 = rnorm(100) 
corr_list = list(corr_1, corr_2, corr_12) 
ttls = c('variance within variable 1', 
     'correlation within variable 1 & 2', 
     'variance within variable 2') 
plots = list() 
for(i in 1:3){ 
    temp_df = data.frame(x=corr_list[[i]]) 
    temp = ggplot(data=temp_df, aes(x=x)) + 
    geom_density()+ 
    ggtitle(ttls[i]) 
    plots[[i]] = temp 
} 
library(gridExtra) ## for grid.arrange() 
library(grid) 
ng <- nullGrob() 
grid.arrange(plots[[1]], plots[[2]],   
      ng, plots[[3]]) 

enter image description here

所以我想是不是明確地說明相關性是指,在圖的頂部有標籤。我應該在上面標題爲「變量1」和「變量2」,並在圖的右側,我有標題爲「變量1」和「變量2」垂直,就像散點圖做什麼。

最終的佈局,我想擁有的是與此類似: enter image description here

然而,不同的是,我的情節需要關閉對角線部分是所有密度圖,和所有的密度圖解獨立的,也就是說,數據不依賴於其他變量,就像在我的最小例子中,我有獨立的圖存儲在列表中(而在成對散點圖中,每個子圖使用一個變量作爲x,一個作爲y)。

+1

@哈克-R,我只是添加了一些細節。 –

回答

1

我假設你有你的情節適當安排,並且你需要的是添加變量標籤。我已經對plot函數進行了一些更改,以刪除標題和軸標籤。

arrangeGrob返回一個也是gtable的grob。因此,可以應用gtable函數來添加標籤。我在下面添加了一些評論。

library(ggplot2) 
library(gridExtra) 
library(grid) 
library(gtable) 

corr_1 = rnorm(100) 
corr_2 = rnorm(100) 
corr_12 = rnorm(100) 
corr_list = list(corr_1, corr_2, corr_12) 
ttls = c('variance within variable 1', 
     'correlation within variable 1 & 2', 
     'variance within variable 2') 
plots = list() 
for(i in 1:3){ 
    temp_df = data.frame(x=corr_list[[i]]) 
    temp = ggplot(data=temp_df, aes(x=x)) + 
    geom_density() + 

    theme(axis.title = element_blank()) #+ 

    # ggtitle(ttls[i]) 
    plots[[i]] = temp 
} 

ng <- nullGrob() 
gp <- arrangeGrob(plots[[1]], plots[[2]],   
      ng, plots[[3]]) 

# The gp object is a gtable; 
# thus gtable functions can be applied to add the the necessary labels 

# A list of text grobs - the labels 
vars <- list(textGrob("Variable 1"), textGrob("Variable 2")) 

# So that there is space for the labels, 
# add a row to the top of the gtable, 
# and a column to the left of the gtable. 
gp <- gtable_add_cols(gp, unit(1.5, "lines"), 0) 
gp <- gtable_add_rows(gp, unit(1.5, "lines"), 0) 

# Add the label grobs. 
# The labels on the left should be rotated; hence the edit. 
# t and l refer to cells in the gtable layout. 
# gtable_show_layout(gp) shows the layout. 
gp <- gtable_add_grob(gp, lapply(vars, editGrob, rot = 90), t = 2:3, l = 1) 
gp <- gtable_add_grob(gp, vars, t = 1, l = 2:3) 

# Draw it 
grid.newpage() 
grid.draw(gp) 

enter image description here

+0

感謝您的回答,這真的幫助我瞭解gridExtra。 –