Reputation: 2961
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 (e.g. 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:
If I set hjust=2
then the text is no longer properly flushed right:
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")
Upvotes: 4
Views: 2293
Reputation: 2961
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)
Upvotes: 4
Reputation: 859
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"))
Upvotes: 0