簡體   English   中英

R: ggplot2 設置最后一個 plot 在中間與 facet_wrap

[英]R: ggplot2 setting the last plot in the midle with facet_wrap

我正在嘗試使用 facet_wrap 創建一些多圖。 但是,我不確定是否適合我的圖表。 這是一個簡短的可重現示例:

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

這會在此處生成此 plot:

在此處輸入圖像描述

是否可以使用 facet_wrap 方法將第二行中的兩個圖“居中”? 請注意,我不想重新排序圖,我只想將第二行居中

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

在此處輸入圖片說明

您還可以考慮使用egg包中的set_panel_size函數,它可以讓您將多個繪圖的面板大小(寬度、高度)設置為絕對測量值,有關更多詳細信息,請參閱此小插圖

使用 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")
))

在此處輸入圖片說明

實現所需結果的另一個選擇是ggh4x package ,它通過ggh4x::facet_manual通過design參數為 position 增加了一些靈活性:

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)

以防萬一有人想知道如何在網格中從頭開始...

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 包(v0.3.0) 於 2020 年 7 月 3 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM