如何在 ggplot 中增加 *rotated* y-axis 上的文本和标题之间的距离?

How to increase the distance between text and title on *rotated* y-axis in ggplot?

我正在开发一个包含 horizontally-rotated y-axis 标签的自定义 ggplot 主题,我想增加刻度标签和轴标签之间的间距。 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")

您可以在主题选项中使用 plot.margin。您可以将 hjust 设置为 -10,然后更改 plot.margin 中的最后一个数字(参数为 up、right、bot、left)。

举个例子:

库(网格)

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

干杯, 罗曼


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

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

我最终解决了这个问题,它需要调整底层 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)