简体   繁体   English

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

[英]Get margin value between axis.text and axis.title

Short version: How to get the value of the margin between axis.text and axix.title? 简短版本:如何获取axis.text和axix.title之间的边距值?

Long version: I am trying to merge three ggplot graphics. 长版:我正在尝试合并三个ggplot图形。 The scale should be consistent, so I am using rbind (with ggplotGrob) to align the first two graphics. 比例应该是一致的,所以我使用rbind(使用ggplotGrob)来对齐前两个图形。 But the last one has facets, so it is not possible to use this solution for all three. 但最后一个有方面,所以不可能将这个解决方案用于所有三个方面。

My idea is manually set the space between axis.title and axis.text in the third graphic (this can be done using margin with element_text). 我的想法是在第三个图形中手动设置axis.title和axis.text之间的空间(这可以使用margin_text的边距来完成)。 However, to do that I should get the value of this margin in one of the first two graphics. 但是,要做到这一点,我应该在前两个图形之一中获得此边距的值。 I believe that this information is available in the ggplotGrob, but I don't know the path to retrieve this value in the grob structure. 我相信ggplotGrob中提供了这些信息,但我不知道在grob结构中检索此值的路径。

Fake code example: 假代码示例:

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)

Current result: First two graphics with plot area aligned, but not the last one. 当前结果:前两个图形与绘图区域对齐,但不是最后一个。 result plot 结果图

Expected result: The plot area of all three graphics aligned. 预期结果:所有三个图形的绘图区域对齐。

You can align the plots without explicitly worrying about the margin size using ggarrange from the egg package (one of the answers in @bVa's link uses this function): 您可以使用来自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)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM