gpt4 book ai didi

r - 将轴添加到 ggplots 的网格

转载 作者:行者123 更新时间:2023-12-02 02:49:27 25 4
gpt4 key购买 nike

我有一个由多个 ggplots 组成的网格,我想添加一个 x 轴,在绘图之间添加轴刻度和注释。没有比为轴创建自定义绘图并使用 arrangeGrob 添加它更好的解决方案了。但它们与图不一致(我在数字应该画的地方画了箭头)。下面还有一个我不想要的大空白区域。

我还需要一个 y 轴的模拟。

library(ggplot2)
library(gridExtra)
library(ggpubr)
library(grid)

# Create a grid with several ggplots
p <-
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
theme_transparent() +
theme(plot.background = element_rect(color = "black"))

main.plot <- arrangeGrob(p, p, p, p, p, p, p, p, ncol = 4, nrow = 2)
# grid.draw(main.plot)

# Now add an x axis to the main plot
x.breaks <- c(0, 1, 2.5, 8, 10)
p.axis <- ggplot() +
ylim(-0.1, 0) +
xlim(1, length(x.breaks)) +
ggpubr::theme_transparent()

for (i in seq_along(x.breaks)) {
p.axis <- p.axis +
geom_text(aes_(x = i, y = -0.01, label = as.character(x.breaks[i])), color = "red")
}
# p.axis

final.plot <- arrangeGrob(main.plot, p.axis, nrow = 2)
grid.draw(final.plot)

enter image description here

感谢任何帮助。

最佳答案

注意:在下面的代码中,我假设您的网格中的每个图都具有相等的宽度/高度,并且使用等间距的标签位置。如果不是这种情况,您将不得不自己调整位置。

将 x 轴添加到 main.plot:

library(gtable)

# create additional row below main plot
# height may vary, depending on your actual plot dimensions
main.plot.x <- gtable_add_rows(main.plot, heights = unit(20, "points"))

# optional: check results to verify position of the new row
dev.off(); gtable_show_layout(main.plot.x)

# create x-axis labels as a text grob
x.axis.grob <- textGrob(label = x.breaks,
x = unit(seq(0, 1, length.out = length(x.breaks)), "npc"),
y = unit(0.75, "npc"),
just = "top")

# insert text grob
main.plot.x <- gtable_add_grob(main.plot.x,
x.axis.grob,
t = nrow(main.plot.x),
l = 1,
r = ncol(main.plot.x),
clip = "off")

# check results
dev.off(); grid.draw(main.plot.x)

with x-axis labels added

您可以对 y 轴执行相同的操作:

# create additional col
main.plot.xy <- gtable_add_cols(main.plot.x, widths = unit(20, "points"), pos = 0)

# create y-axis labels as a text grob
y.breaks <- c("a", "b", "c") # placeholder, since this wasn't specified in the question
y.axis.grob <- textGrob(label = y.breaks,
x = unit(0.75, "npc"),
y = unit(seq(0, 1, length.out = length(y.breaks)), "npc"),
just = "right")

# add text grob into main plot's gtable
main.plot.xy <- gtable_add_grob(main.plot.xy,
y.axis.grob,
t = 1,
l = 1,
b = nrow(main.plot.xy) - 1,
clip = "off")

# check results
dev.off(); grid.draw(main.plot.xy)

with y-axis labels

(注意上面x轴先y轴的顺序不能盲目调换,如果是添加行/列,经常使用gtable_show_layout()检查是个好习惯最新的 gtable 对象尺寸,并确保将新的 grob 插入正确的单元格中。)

最后,让我们在所有边上添加一些缓冲区,这样标签和绘图边框就不会被切断:

final.plot <- gtable_add_padding(main.plot.xy,
padding = unit(20, "points"))

dev.off(); grid.draw(final.plot)

with buffer

关于r - 将轴添加到 ggplots 的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com