r - 如何增加ggplot中*旋转* y轴上文本和标题之间的距离?

标签 r ggplot2

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

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

image with hjust=1

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

image with 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")

最佳答案

我最终想通了这一点,它需要调整底层的 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)

关于r - 如何增加ggplot中*旋转* y轴上文本和标题之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28701200/

相关文章:

r - ggplot2,排列多个图,大小相同,之间没有间隙

regex - R 中 SQL LIKE 运算符的等价物

r - 如何在同一图表中将(n 未知)数量的数据系列绘制为 geom_line

r - 使用 ggplot2、aes_string 和 reorder 制作绘图函数

r - 为 mlogit 格式化数据

ggplot2 - 使用facet_wrap_paginate分离出facet_wrap

r - 带有重叠标签的 geom_text()

r - 从多个 URL 自动下载,处理反馈对话框/cookie

r - checkError(res) : Undefined error in httr call. httr 输出中的错误:无法连接到本地主机端口 4445:连接被拒绝

mysql - "Too few parameters"尝试连接到 R 中的 Microsoft Access 数据库