Reputation: 2583
library(ggplot2)
p <- ggplot(mtcars, aes(x=mpg, y=wt*1000, color = factor(cyl))) + geom_point()
p + ylab("weight (lb)") +theme_bw()
I would like to move 5000, 4000, 3000, and 2000 closer to the vertical axis. I know one can instead use theme(axis.title.y=element_text(vjust=0.36,hjust=.36))
or similar to move the axis title further away, but sometimes I really want to move the tick labels, not the axis title.
Upvotes: 5
Views: 15342
Reputation: 3311
Version 2.0.0
introduced the new margin()
which we can use here:
ggplot(mtcars, aes(x = mpg, y = wt*1000, color = factor(cyl))) +
geom_point() +
ylab("weight (lb)") +
theme_bw() +
theme(axis.text.y = element_text(margin = margin(r = 0)))
My reading of this issue on github is, that you should use vjust
only for the y-axis
and hjust
only for the x-axis
. To alter the distance between tick-label and axis, use margin(r = x)
on the y-axis, and margin(t = x)
on the x-axis
. Doc for element_text
reads: "When creating a theme, the margins should be placed on the side of the text facing towards the center of the plot."
Upvotes: 8
Reputation: 98419
One solution would be to use axis.ticks.margin=
element of theme()
and set it to 0. But this will influence both axis.
library(ggplot2)
library(grid)
ggplot(mtcars, aes(x=mpg, y=wt*1000, color = factor(cyl))) + geom_point() +
ylab("weight (lb)") +theme_bw()+
theme(axis.ticks.margin=unit(0,'cm'))
Upvotes: 5