代码之家  ›  专栏  ›  技术社区  ›  Joe

在ggplot2中显式设置面板大小(不仅仅是打印大小)

  •  5
  • Joe  · 技术社区  · 7 年前

    panel.width = unit(3, "in"), panel.height = unit(4, "in")

    我见过设置整个绘图大小的解决方案,或者使用 egg 包裹但是没有什么能让我明确设置面板的大小。

    library(dplyr)
    library(ggplot2)
    library(tibble)
    
    ds_mt <- mtcars %>% rownames_to_column("model")
    mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
    mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)
    
    p_short <- 
        mt_short %>% 
        ggplot(aes(x = model, y = mpg)) + 
        geom_col() + 
        coord_flip()
    
    p_short
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  7
  •   Tung    6 年前

    你可以用 set_panel_size() egg 包裹

    library(tibble)
    library(dplyr)
    library(ggplot2)
    
    ds_mt <- mtcars %>% rownames_to_column("model")
    mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
    mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)
    
    p_short <- 
      mt_short %>% 
      ggplot(aes(x = model, y = mpg)) + 
      geom_col() + 
      coord_flip()
    
    library(egg)
    library(grid)
    p_fixed <- set_panel_size(p_short,
                              width  = unit(10, "cm"),
                              height = unit(4, "in"))
    grid.newpage()
    grid.draw(p_fixed)
    

    于2018-11-13由 reprex package

        2
  •  3
  •   teunbrand    5 年前

    ggh4x包具有 similar function 另一个答案中的鸡蛋溶液。稍微方便一点的是,在使用函数之后,绘图仍然是有效的ggplot,因此它可以与 ggsave() 之后可以添加其他层(免责声明:我写了ggh4x)

    library(dplyr)
    library(ggplot2)
    library(tibble)
    library(ggh4x)
    
    ds_mt <- mtcars %>% rownames_to_column("model")
    mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
    mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)
    
    mt_short %>% 
      ggplot(aes(x = model, y = mpg)) + 
      geom_col() + 
      coord_flip() +
      force_panelsizes(rows = unit(4, "in"),
                       cols = unit(3, "in"))
    

    reprex package (1.0.0版)

    推荐文章