r - 获取 axis.text 和 axis.title 之间的边距值

标签 r ggplot2 gridextra

简短版: 如何获取axis.text和axix.title之间的边距值?

长版: 我正在尝试合并三个 ggplot 图形。比例应该是一致的,所以我使用 rbind(与 ggplotGrob)对齐前两个图形。但是最后一个有刻面,所以不可能对所有三个都使用这个解决方案。

我的想法是在第三个图形中手动设置 axis.title 和 axis.text 之间的空间(这可以使用 margin 和 element_text 来完成)。 但是,要做到这一点,我应该在前两个图形之一中获得此边距的值。我相信此信息在 ggplotGrob 中可用,但我不知道在 grob 结构中检索此值的路径。

伪代码示例:

library(ggplot2)
library(gridExtra)

a <- ggplotGrob( ggplot(iris[iris$Species != "setosa",], aes(x=Sepal.Length, y=Petal.Width*100000, color=Species)) + geom_line()  + theme(legend.position="none"))

b <- ggplotGrob( ggplot(iris[iris$Species != "setosa",], aes(x=Sepal.Length, y=Petal.Length, color=Species)) + geom_line() + theme(legend.position="none"))

c <- ggplotGrob(ggplot(head(mpg, 100), aes(class)) + geom_bar() + facet_grid(.~manufacturer, scales="free_x"))

g1 <- rbind(a, b, size="first")
grid.arrange(g1, c, ncol=1)

当前结果: 前两个绘图区域对齐的图形,但不是最后一个。 result plot

预期结果: 所有三个图形的绘图区域对齐。

最佳答案

您可以使用 egg 包中的 ggarrange 对齐绘图,而无需明确担心边距大小(@bVa 链接中的答案之一使用此函数):

#devtools::install_github("baptiste/egg")
library(egg)
library(ggplot2)

a <- ggplot(iris[iris$Species != "setosa",], aes(x=Sepal.Length, y=Petal.Width*100000, color=Species)) + geom_line()  + theme(legend.position="none")

b <- ggplot(iris[iris$Species != "setosa",], aes(x=Sepal.Length, y=Petal.Length, color=Species)) + geom_line() + theme(legend.position="none")

c <- ggplot(head(mpg, 100), aes(class)) + geom_bar() + facet_grid(.~manufacturer, scales="free_x")

ggarrange(a,b,c, ncol=1)

enter image description here

关于r - 获取 axis.text 和 axis.title 之间的边距值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793194/

相关文章:

r - 如何在 gtable 内部使用解析并保留尾随零

c++ - C++ 中的分区和组合(组合)实现

r - 根据最近的时间戳在 R 中加入两个数据帧

r - 使用 dplyr 总结逻辑数据帧

r - 根据ggplot2中类别的比例调整(堆叠)条宽

grid - 使用 grid.arrange 为使用 gridExtra::grid.arrange 制作的多个图添加标题

R:dplyr 总结,仅对唯一值求和

r - 在 x 轴上绘制两行中因子的交互作用

r - ggplot2,更改标题大小

r - 使用 grid.arrange 更改多图 ggplot2 中的标题