我想在 ggplot 中制作面图,但我希望纵横比固定(1:1)并标记每个 x 轴。这是示例:
data <- expand.grid(x = 1:10, y = 1:10)
data$col <- rpois(nrow(data), lambda = 10)
data <- rbind(cbind(data, "type" = "a"), cbind(data, "type" = "b"))
ggplot() +
geom_tile(data = data, aes(x = x, y = y, fill = col)) +
labs(x = "very long label of x") +
facet_wrap(~type, ncol = 2) +
coord_fixed()
这给出了这个结果:
但我想要 each 图下 x 轴的标签。我想使用
scales = "free"
希望得到我想要的东西,但我得到一个错误:
Error in `draw_panels()`:
! `facet_wrap()` can't use free scales with `coord_fixed()`
有人可以帮助我吗?我可以使用
grid.extra
来组合两个单独的图,但这在尝试共享图例时再次产生额外的工作。有简单的解决办法吗?
TBMK,为每个面板获取轴标题的唯一选择是合并两个单独的图,我会选择
patchwork
,因为它可以轻松收集指南。如果需要的话,还需要做一些工作来消除重复的 y 轴:
library(ggplot2)
library(patchwork)
set.seed(123)
data |>
split(~type) |>
purrr::imap(\(x, y) {
remove_y <- if (y != "a") {
scale_y_continuous(
breaks = NULL, name = NULL
)
}
ggplot() +
geom_tile(data = x, aes(x = x, y = y, fill = col)) +
labs(x = "very long label of x") +
facet_wrap(~type) +
coord_fixed() +
remove_y
}) |>
wrap_plots(ncol = 2) +
plot_layout(guides = "collect")