facet_grid并且facet_wrap每個都有自己的局限性。
facet_wrap沒有space = "free"引數,導致繪圖的 y 軸不吸引人(有關代碼,請參閱
facet_grid受到側面標簽的限制(有關代碼,請參閱
已經提供了將facet_grid標簽移動到頂部的解決方案(請參閱
要求是;頂部的標簽,y 軸上的適當間距,并且兩個 x 軸使用相同的比例。
uj5u.com熱心網友回復:
這是您要查找的輸出嗎?
library(tidyverse)
library(gtable)
library(grid)
library(gridExtra)
#>
#> Attaching package: 'gridExtra'
#> The following object is masked from 'package:dplyr':
#>
#> combine
p1 <- mtcars %>%
rownames_to_column() %>%
filter(carb %in% c(1, 3, 6)) %>%
ggplot(aes(x = disp, y = rowname))
geom_point()
xlim(c(0, 450))
facet_grid(carb ~ ., scales = "free_y", space = "free_y")
theme(panel.spacing = unit(1, 'lines'),
strip.text.y = element_text(angle = 0))
gt1 <- ggplotGrob(p1)
panels <-c(subset(gt1$layout, grepl("panel", gt1$layout$name), se=t:r))
for(i in rev(panels$t-1)) {
gt1 = gtable_add_rows(gt1, unit(0.5, "lines"), i)
}
panels <-c(subset(gt1$layout, grepl("panel", gt1$layout$name), se=t:r))
strips <- c(subset(gt1$layout, grepl("strip-r", gt1$layout$name), se=t:r))
stripText = gtable_filter(gt1, "strip-r")
for(i in 1:length(strips$t)) {
gt1 = gtable_add_grob(gt1, stripText$grobs[[i]]$grobs[[1]], t=panels$t[i]-1, l=5)
}
gt1 = gt1[,-6]
for(i in panels$t) {
gt1$heights[i-1] = unit(0.8, "lines")
gt1$heights[i-2] = unit(0.2, "lines")
}
p2 <- mtcars %>%
rownames_to_column() %>%
filter(carb %in% c(2, 4, 8)) %>%
ggplot(aes(x = disp, y = rowname))
geom_point()
xlim(c(0, 450))
facet_grid(carb ~ ., scales = "free_y", space = "free_y")
theme(panel.spacing = unit(1, 'lines'),
strip.text.y = element_text(angle = 0))
gt2 <- ggplotGrob(p2)
#> Warning: Removed 2 rows containing missing values (geom_point).
panels <-c(subset(gt2$layout, grepl("panel", gt2$layout$name), se=t:r))
for(i in rev(panels$t-1)) {
gt2 = gtable_add_rows(gt2, unit(0.5, "lines"), i)
}
panels <-c(subset(gt2$layout, grepl("panel", gt2$layout$name), se=t:r))
strips <- c(subset(gt2$layout, grepl("strip-r", gt2$layout$name), se=t:r))
stripText = gtable_filter(gt2, "strip-r")
for(i in 1:length(strips$t)) {
gt2 = gtable_add_grob(gt2, stripText$grobs[[i]]$grobs[[1]], t=panels$t[i]-1, l=5)
}
gt2 = gt2[,-6]
for(i in panels$t) {
gt2$heights[i-1] = unit(0.8, "lines")
gt2$heights[i-2] = unit(0.2, "lines")
}
grid.arrange(gt1, gt2, ncol = 2)

由reprex 包(v2.0.1)于 2021 年 12 月 16 日創建
如果沒有,需要做哪些改變?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387235.html
