在ggplot2中明确设置面板尺寸(不仅是绘图尺寸)

时间:2018-11-13 16:31:43

标签: r ggplot2

是否可以在ggplot中显式设置面板尺寸(即灰色网格面板)?我想象(但找不到)有一些ggplot扩展名,允许类似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

2 个答案:

答案 0 :(得分:3)

您可以使用egg软件包中的set_panel_size()功能

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()

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)

reprex package(v0.2.1.9000)于2018-11-13创建

答案 1 :(得分:3)

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 (v1.0.0) 于 2021 年 4 月 21 日创建

相关问题