簡體   English   中英

為ggplot中的多個圖添加帶線/箭頭的公共軸標題

[英]Add common axis titles with lines/arrows for multiple plots in ggplot

我有我的虛擬數據並繪制為:

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指向側面。 是否可以在此圖中進行此類更改? 請注意,這些ggobject來自循環,因此facet_grid對我不起作用。

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()

ggplot2 facet_wrap 或者,您可以剝離構面標簽並進行注釋:

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')

ggplot2手動字幕

最后,添加線條和箭頭,這是一種手動的方法。 當我調整圖的大小時,線條也弄亂了:

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()

軸下方的ggplot線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM