1

facet_wrap()因没有space = "free"争论而被认可(https://github.com/tidyverse/ggplot2/issues/2933)。这可能会导致绘图 y 轴上的间距问题。

在此处输入图像描述

使用以下代码创建上图:

library(tidyverse)

p <-
  mtcars %>%
  rownames_to_column() %>%
  ggplot(aes(x = disp, y = rowname)) + geom_point() +
  facet_wrap(~ carb, ncol = 1, scales = "free_y")

facet_grid另一方面有space = "free"论据。允许良好的 y 轴间距。

在此处输入图像描述

使用以下代码创建上图:

p <-
  mtcars %>%
  rownames_to_column() %>%
  ggplot(aes(x = disp, y = rowname)) + geom_point() + 
  facet_grid(carb ~ ., scales = "free_y", space = "free_y")

问题在于标签在侧面,而不是顶部。有时我的构面标签较长,而构面中的行数很少。这意味着刻面标签被切断。

包中有一个解决方案(ilarischeinin 在https://github.com/tidyverse/ggplot2/issues/2933上发表评论)。

p <-
  mtcars %>%
  rownames_to_column() %>%
  ggplot(aes(x = disp, y = rowname)) + geom_point()

p + ggforce::facet_col(vars(carb), scales = "free_y", space = "free")

有一些限制。似乎无法实现此功能。有什么方法可以产生相同的结果,facet_wrap()以便我可以利用这个ncol()论点?

4

1 回答 1

2

这是基于https://stackoverflow.com/a/29022188/12957340的潜在解决方法:

library(tidyverse)
library(gtable)
library(grid)

p1 <- mtcars %>%
  rownames_to_column() %>%
  ggplot(aes(x = disp, y = rowname)) + geom_point() +
  facet_grid(carb ~ ., scales = "free_y", space = "free_y") +
  theme(panel.spacing = unit(1, 'lines'),
        strip.text.y = element_text(angle = 0))

gt <- ggplotGrob(p1)
panels <-c(subset(gt$layout, grepl("panel", gt$layout$name), se=t:r))
for(i in rev(panels$t-1)) {
  gt = gtable_add_rows(gt, unit(0.5, "lines"), i)
}
panels <-c(subset(gt$layout, grepl("panel", gt$layout$name), se=t:r))
strips <- c(subset(gt$layout, grepl("strip-r", gt$layout$name), se=t:r))
stripText = gtable_filter(gt, "strip-r")
for(i in 1:length(strips$t)) {
  gt = gtable_add_grob(gt, stripText$grobs[[i]]$grobs[[1]], t=panels$t[i]-1, l=5)
}
gt = gt[,-6]
for(i in panels$t) {
  gt$heights[i-1] = unit(0.8, "lines")
  gt$heights[i-2] = unit(0.2, "lines")
}
grid.newpage()
grid.draw(gt)

reprex 包于 2021-12-15 创建(v2.0.1)

我不清楚“我最终想要一个两列图”是什么意思,但如果你能想出一个例子来说明你的“最终”预期结果,我可以尝试调整这种方法,看看它是否可行或不是。

于 2021-12-14T22:39:56.470 回答