【问题标题】:How to increase the distance between text and title on *rotated* y-axis in ggplot?如何在ggplot中增加*旋转* y轴上的文本和标题之间的距离?
【发布时间】:2015-02-24 16:34:27
【问题描述】:

我正在开发一个自定义 ggplot 主题,其中包括水平旋转的 y 轴标签,并且我想增加刻度标签和轴标签之间的间距。 This post 建议调整 vjust 参数,但在这种情况下不合适。对齐方式(例如框内的左对齐或右对齐)与该框相对于刻度标签的间距不同。

例如使用axis.title.y=element_text(angle=0, vjust=1, hjust=1)),那么我得到了正确的对齐方式,但它离刻度标签太近了:

如果我设置hjust=2,则文本不再正确刷新:

我使用过margin 主题选项,但我认为它们不适用于这里。有什么想法吗?

编辑这是一个简单的 MWE,用于按要求进行测试:

df <- data.frame(x=1:10, y=1:10)
ggplot(df, aes(x,y)) +
    geom_line() +
    theme(axis.title.y=element_text(angle=0, vjust=1, hjust=1)) +
    labs(y="This\nis a\nreally long\naxis\nlabel")

【问题讨论】:

  • 如果有一个可重现的示例来测试解决方案,那就太好了。

标签: r ggplot2


【解决方案1】:

我最终想通了,它需要调整底层的 gtable。

library(ggplot2)
library(grid)
library(gtable)
df <- data.frame(x=1:10, y=1:10)
gg <- ggplot(df, aes(x,y)) +
    geom_line() +
    theme(axis.title.y=element_text(angle=0, vjust=1, hjust=1)) +
    labs(y="This\nis a\nreally long\naxis\nlabel")

# Get the table for the ggplot object
g <- ggplotGrob(gg)

# Insert a new column 0.25 inches wide after the second column
# Use gtable_show_layout(g) to figure out which column number to use
g2 <- gtable_add_cols(g, width=unit(0.25, "in"), pos=2)

# Plot the result
grid.draw(g2)

【讨论】:

    【解决方案2】:

    您可以在主题选项中使用 plot.margin。您可以将 hjust 设置为 -10,然后更改 plot.margin 中的最后一个数字(参数为上、右、机器人、左)。

    试一试:

    库(网格)

    df <- data.frame(x=1:10, LongAxisLabel=1:10)
    ggplot(df, aes(x,LongAxisLabel)) +
      geom_line() +
      theme(axis.title.y=element_text(angle=0, vjust=1, hjust=-1))+
      theme(plot.margin = unit(c(1,1,1,1), "cm"))
    

    干杯, 罗曼


    根据您对对齐问题的查询。我用我放在标签周围的函数表达式()更新了代码。见下文,我得到我认为你想要的东西。让我们知道。

    library(grid)
    df <- data.frame(x=1:10, y=1:10)
    ggplot(df, aes(x,y)) + 
      geom_line() + 
      theme(axis.title.y=element_text(angle=0, vjust=1, hjust=-1), plot.margin=unit(c(3,1,1,3), "cm")) + 
      labs(y=expression("This\nis a\nreally long\naxis\nlabel"))
    

    【讨论】:

    • 这不起作用。尝试以下操作,您会发现多余的行没有正确对齐。 ggplot(df, aes(x,y)) + geom_line() + theme(axis.title.y=element_text(angle=0, vjust=1, hjust=-1), plot.margin=unit(c(1,1,1,1), "cm")) + labs(y="This\nis a\nreally long\naxis\nlabel")
    • 嗨@jkeirstead我已经更新了上面的答案,看看,看看是否能解决你的问题。
    • 谢谢,但不幸的是,该代码只是增加了轴标题左侧的空间。如上图所示,我正在寻找右对齐文本,轴标题和刻度标签之间有一个空格。
    • 我明白了。对不起,我到处看了,轴标题的格式真的很差。 expression() 将帮助您获得标签 "together" ,至于对齐我没有找到强制右对齐的方法。
    • 这不可能!
    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2017-02-05
    • 2021-11-25
    • 2021-12-19
    • 2017-02-14
    相关资源
    最近更新 更多