【问题标题】:Add common axis titles with lines/arrows for multiple plots in ggplot在 ggplot 中为多个绘图添加带有线/箭头的公共轴标题
【发布时间】:2019-09-05 19:59:11
【问题描述】:

我有我的虚拟数据并绘制为:

library(ggpubr)
d1 <- data.frame(x = c(5, 2, 3), y = c(7, 5, 6))
d2 <- data.frame(x = c(3, 2, 1), y = c(6, 5, 4))
d3 <- data.frame(x = c(5, 6, 3), y = c(8, 6, 6))
d4 <- data.frame(x = c(3, 8, 1), y = c(6, 3, 5))
bp <- list(d1, d2, d3, d4)
bp

cbp <- vector("list", length = 4)
for (i in 1:4) {
  cbp[[i]] <- ggplot(bp[[i]], aes(x= x, y = y))+geom_point()
}

ggarrange(plotlist = cbp, labels = c("A", "B", "C", "D"), ncol = 2, nrow = 2)

代替所有四个图中的 X 和 Y 轴标题,我希望有一个共同的 X 和 Y 标题,其中 Y 向上和向下,X 指向侧面。有可能在这个情节中做出这样的改变吗? 请注意这些 ggobjects 来自循环,所以 facet_grid 对我不起作用。

【问题讨论】:

  • @akrun 我的意思是说箭头指示 Y 向上和向下,X 指向侧面
  • 我有几个 hacky 解决方案,但您能否首先为我们提供一个更通用的示例(而不是一个具有相同 x 和 y 的 df,更接近您的实际问题,这会导致不同的图和轴范围)。
  • @M-- 我已经更新了数据。
  • 线条在哪里,底部和左侧轴线?在所有地块上?
  • @camille 左边一行,底部一行。并非在所有地块上。

标签: r ggplot2


【解决方案1】:

虽然 OP 提到由于循环而无法使用 facet_grid,但循环并没有什么特别之处可以阻止它被使用:

library(data.table)
dt <- rbindlist(bp, id = 'dt_list')

p <- ggplot(dt, aes(x = x, y = y))+
  geom_point()+
  facet_wrap(vars(dt_list), scales = 'free', strip.position = 'left')

p+theme_classic()

或者,您可以剥离构面标签并对其进行注释:

caption_helper <- dt[, .(y = max(y), x= min(x)), by = dt_list]

p+theme(strip.text = element_blank(), strip.background = element_blank())+
  geom_text(data = caption_helper, aes(x = x, y = y, label = dt_list), fontface = 'bold')

最后,要添加线条和箭头,这里有一种手动的方法。当我调整情节大小时,线条也变得混乱:

p+theme(strip.text = element_blank(), strip.background = element_blank())+
  geom_text(data = caption_helper, aes(x = x, y = y, label = dt_list), fontface = 'bold')

library(grid)
pushViewport(viewport())
grid.lines(x = unit(c(0.1,0.95), 'npc'),
           y = unit(0.036, 'npc'),
           gp = gpar(col = "black"),
           arrow = arrow(angle = 30, length = unit(0.25, "inches"),
                         ends = "last", type = "open"))

grid.lines(x = 0.03,
           y = c(0.1,0.95),
           gp = gpar(col = "black"),
           arrow = arrow(angle = 30, length = unit(0.25, "inches"),
                         ends = "last", type = "open"))

popViewport()

【讨论】:

  • 谢谢,但是如何添加线/箭头来覆盖轴?
  • 你能注释你的吗?我不确定这些线条/箭头。
  • 我可以在 Inkscape 中添加这一行,但只是想在 R 中尝试。该行(带箭头)只是为了显示它跨越图左侧的 Y 和底部的 X数字。左边一长线,底部一长线
  • @MAPK,见编辑。它并不完美,但会导致箭头。
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 2021-04-07
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多