我想對齊幾個圖的區域,每個圖都由 RMarkdown 檔案(最好是 .html)中的單獨塊“很好地”創建。我的問題:由于 y 軸文本的長度不同。繪制的區域沒有完全重疊(很遺憾,因為我的實際 x 軸是幾個月)。
設定fig.width=和out.width=在這里沒有幫助,因為他們考慮了軸文本長度。
虛擬資料塊:
require(ggplot2)
df = expand.grid(y = LETTERS,
x = paste0('A', 1:10),
stringsAsFactors = FALSE)
set.seed(42)
df$fill = rnorm(nrow(df))
df2 = df
df2$y = unlist(lapply(lapply(df2$y, function(x) rep(x, 10)), paste0, collapse = ''))
情節塊1:
gg1 = ggplot(df, aes(y = y, x = x, fill = fill))
geom_tile()
gg1
情節塊2:
gg2 = ggplot(df2, aes(y = y, x = x, fill = fill))
geom_tile()
gg2
RMarkdown 檔案中的圖應如下所示(紅線突出顯示所需的對齊方式):

我用 patchwork 包實作了這一點。但是,像這樣我只能使用一個塊而不是多個。
拼湊-情節-塊:
require(patchwork)
gg1 / gg2
plot_annotation(tag_levels = 'A')
uj5u.com熱心網友回復:
編輯(更整潔?)解決方案: cowplot::align_plots
稍微玩一下cowplot::align_plots,就可以設定標準面板寬度以在所有圖形中使用。但是,要在構建每個圖形“盲”到即將到來的圖形時跨塊執行此操作,您可以創建一個帶有標簽的“模板”圖(gg_set如下所示)。然后,每個后續圖形都將采用此未使用圖的大小:
require(ggplot2)
df <- expand.grid(y = LETTERS,
x = paste0('A', 1:10),
stringsAsFactors = FALSE)
set.seed(42)
df$fill = rnorm(nrow(df))
df2 <- df
df2$y <-
unlist(lapply(lapply(df2$y, function(x)
rep(x, 5)), paste0, collapse = ''))
# df for setting max size needed - might need experimented with
dfset <- df
dfset$y <-
unlist(lapply(lapply(df$y, function(x)
rep(x, 10)), paste0, collapse = ''))
# 'template' plot
gg_set <- ggplot(dfset, aes(y = y, x = x, fill = fill))
geom_tile()
require(cowplot)
# Chunk 1
gg1 <- ggplot(df, aes(y = y, x = x, fill = fill))
geom_tile()
ggs <- align_plots(gg_set, gg1, align = "v")
# Only extracting relevant graph.
ggdraw(ggs[[2]])

# Chunk 2
gg2 <- ggplot(df2, aes(y = y, x = x, fill = fill))
geom_tile()
ggs <- align_plots(gg_set, gg2, align = "v")
ggdraw(ggs[[2]])

由reprex 包(v2.0.1)于 2021 年 12 月 17 日創建
不整潔的前解決方案
我以前使用過一個公認的凌亂解決方案,它實際上只是涉及用上下空白行填充所有標簽以大于最大長度:
require(ggplot2)
#> Loading required package: ggplot2
df <- expand.grid(y = LETTERS,
x = paste0('A', 1:10),
stringsAsFactors = FALSE)
set.seed(42)
df$fill = rnorm(nrow(df))
df2 <- df
df2$y <-
unlist(lapply(lapply(df2$y, function(x)
rep(x, 10)), paste0, collapse = ''))
df$y <-
paste0(paste0(rep(" ", 40), collapse = ""), "\n", df$y, "\n", paste0(rep(" ", 40)))
df2$y <-
paste0(paste0(rep(" ", 40), collapse = ""), "\n", df2$y, "\n", paste0(rep(" ", 40)))
gg1 <- ggplot(df, aes(y = y, x = x, fill = fill))
geom_tile()
gg1

gg2 <- ggplot(df2, aes(y = y, x = x, fill = fill))
geom_tile()
gg2

我希望他們是一個更正式的解決方案,允許靜態面板大小調整,我期待聽到其他答案。但已將其用作快速修復!
由reprex 包(v2.0.1)于 2021 年 12 月 17 日創建
uj5u.com熱心網友回復:
該錯落有致包還包括功能align_patches(),其作業原理類似cowplot::align_plots()。
gg_l = patchwork::align_patches(gg1,
gg2)
情節塊1:
gg_l[[1]]
情節塊2:
gg_l[[2]]
來自問題的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387233.html
