简体   繁体   中英

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

I'm developing a custom ggplot theme which includes horizontally-rotated y-axis labels, and I want to increase the spacing between the tick labels and the axis labels. This post suggests adjusting the vjust parameter but that isn't appropriate in this case. Alignment (eg left or right within the box) is different from the spacing of that box relative to the tick label.

For example with axis.title.y=element_text(angle=0, vjust=1, hjust=1)) , then I get the correct alignment but it's too close to the tick labels:

hjust = 1的图像

If I set hjust=2 then the text is no longer properly flushed right:

hjust = 2的图像

I've played with the margin theme options but I don't think they are applicable here. Any ideas?

EDIT Here's a simple MWE for testing as requested:

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

I figured this out eventually, and it requires tweaking the underlying 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)

You can use the plot.margin in a theme option. You could set your hjust to be -10 and then change the last figure in the plot.margin (the arguments are up,right,bot,left).

Try for example :

library(grid)

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

Cheers, Romain


Following your query on the alignment issue. I updated the code with the function expression() that I put around the label. See below and I obtain I think something along what you wanted. Let us know.

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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