2016-09-27 87 views
3

我正在組合tile的facet圖。我希望每個瓷磚都是正方形的,或者至少採用相同的高度和寬度。在grid.arrange中使用layout_matrix時的繪圖區域寬度

到目前爲止,我已設法使用layout_matrix給每個瓷磚行等高度。當我試圖修復每個瓷磚列的相等寬度時(整個圖),我被卡住了。

基於mtcars,試圖說明我的陰謀佈局(實際數據的方式更加複雜)的某些代碼:

library("tidyverse") 
library("gridExtra") 

df0 <- mtcars %>% 
    group_by(cyl) %>% 
    count() 

df1 <- mtcars %>% 
    rownames_to_column("car") %>% 
    mutate(man = gsub("([A-Za-z]+).*", "\\1", car)) 

g <- list() 
for(i in 1:nrow(df0)){ 
    g[[i]] <- ggplot(data = df1 %>% filter(cyl == df0$cyl[i]), 
        mapping = aes(x = "", y = car, fill = qsec)) + 
    geom_tile() + 
    facet_grid(man ~ ., scales = "free_y", space = "free") + 
    labs(x = "", y = "") + 
    guides(fill = FALSE) + 
    theme(strip.text.y = element_text(angle=0)) + 
    coord_fixed() 
} 

m0 <- cbind(c(rep(1, df0$n[1]), rep(NA, max(df0$n) - df0$n[1])), 
      c(rep(2, df0$n[2]), rep(NA, max(df0$n) - df0$n[2])), 
      c(rep(3, df0$n[3]), rep(NA, max(df0$n) - df0$n[3]))) 
grid.arrange(grobs = g, layout_matrix = m0) 

將會產生這個圖(減去我的MS油漆技能):

enter image description here

假定條形文本和y軸中標籤的不同長度導致繪圖區域的寬度不同。不知道我怎麼可以避免這種行爲?我以爲我可以創造大facet_grid,但我無法接近上述地塊的佈局。

回答

2

原來這是一件相當棘手的事情。幸運的是,cowplot::plot_grid已經可以進行對齊,導致列的大小相等。我只是採取了這個功能並去除了絨毛,並且將高度從它通常使用的網格圖案中分離出來。我們結束了,沒有工作(全部學分克勞斯維爾克)有點自定義函數:

plot_grid_gjabel <- function(plots, heights) { 
    grobs <- lapply(plots, function(x) { 
    if (!is.null(x)) 
     cowplot:::ggplot_to_gtable(x) 
    else NULL 
    }) 
    num_plots <- length(plots) 
    num_widths <- unique(lapply(grobs, function(x) { 
    length(x$widths) 
    })) 
    num_widths[num_widths == 0] <- NULL 
    max_widths <- do.call(grid::unit.pmax, 
         lapply(grobs, function(x) { x$widths })) 
    for (i in 1:num_plots) { 
    grobs[[i]]$widths <- max_widths 
    } 
    width <- 1/num_plots 
    height <- heights/max(heights) 
    x <- cumsum(width[rep(1, num_plots)]) - width 
    p <- cowplot::ggdraw() 
    for (i in seq_along(plots)) { 
    p <- p + cowplot::draw_grob(grid::grobTree(grobs[[i]]), x[i], 1 - height[i], 
           width, height[i]) 
    } 
    return(p) 
} 

我們可以簡單地把這個像這樣:

plot_grid_gjabel(g, df0$n) 

,導致:

enter image description here