使用facet_wrap将最后一个图设置在中间

gfttwv5a  于 2023-01-15  发布在  其他
关注(0)|答案(4)|浏览(180)

我正在尝试用facet_wrap创建一些多重图。但是我不确定这是否是我的图形的正确方法。下面是一个简短的可重复的例子:

ggplot(airquality, aes(x = Day, y = Temp)) +
  facet_wrap(~Month) + 
  geom_line()

这将生成以下图:

是否可以使用facet_wrap方法将第2行中的两个图“居中”?
请注意,我不想对图重新排序,我只想将第2行居中

ldioqlga

ldioqlga1#

@Tjebo建议使用cowplot,会起作用:

p <- ggplot(mapping = aes(x = Day, y = Temp)) +
  facet_wrap(~Month) + 
  geom_line()

cowplot::plot_grid(
  p %+% subset(airquality, Month < 8),
  p %+% subset(airquality, Month > 7),
  nrow = 2
)

tcbh2hod

tcbh2hod2#

您也可以考虑使用egg包中的set_panel_size函数,该函数允许您将多个图的面板大小(宽度、高度)设置为绝对测量值,有关详细信息,请参阅this vignette
使用Axeman的代码创建绘图

library(egg)
library(gridExtra)
p <- ggplot(mapping = aes(x = Day, y = Temp)) +
  facet_wrap(~Month) + 
  geom_line()

p1 <- p %+% subset(airquality, Month < 8) + labs(x = NULL)
p2 <- p %+% subset(airquality, Month > 7)

现在,指定面板大小后,使用grid.arrange排列图

grid.arrange(grobs = lapply(
  list(p1, p2),
  set_panel_size,
  width = unit(5, "cm"),
  height = unit(4, "cm")
))

nfeuvbwi

nfeuvbwi3#

以防有人想知道如何在网格中从头开始...

library(ggplot2)
library(dplyr)
library(grid)

vps <- c("top_left", "top_mid", "top_right", "bottom_left", "bottom_right")

main_vp  <- vpTree(viewport(name = "main"), vpList(
              viewport(x = 1/6, y = 0.75, width = 1/3, height = 0.5, name = vps[1]),
              viewport(x = 3/6, y = 0.75, width = 1/3, height = 0.5, name = vps[2]),
              viewport(x = 5/6, y = 0.75, width = 1/3, height = 0.5, name = vps[3]),
              viewport(x = 1/3, y = 0.25, width = 1/3, height = 0.5, name = vps[4]),
              viewport(x = 2/3, y = 0.25, width = 1/3, height = 0.5, name = vps[5])))

grid.newpage()
pushViewport(main_vp)

plots <- lapply(1:5, function(i){ 
  seekViewport(vps[i])
  invisible(grid.draw(ggplotGrob(
    
    ggplot(filter(airquality, Month == levels(as.factor(airquality$Month))[i]), 
           mapping = aes(Day, Temp)) + 
      geom_line() + 
      facet_grid(.~Month)
    
)))})

reprex package(v0.3.0)于2020年7月3日创建

rsaldnfx

rsaldnfx4#

实现所需结果的另一个选项是ggh4x封装,它通过ggh4x::facet_manual增加了一些灵活性,以便通过design参数定位面:

library(ggplot2)
library(ggh4x)

base <- ggplot(airquality, aes(x = Day, y = Temp)) +
  geom_line()

design <- c(
"
AABBCC
#DDEE#
"
)

base + ggh4x::facet_manual(~Month, design = design)

design <- c(
"
AABBCC
DDDEEE
"
)
base + ggh4x::facet_manual(~Month, design = design)

相关问题