Alex Holcombe
Alex Holcombe

Reputation: 2583

How does one move the tick labels closer to the axis?

library(ggplot2)
p <- ggplot(mtcars, aes(x=mpg, y=wt*1000, color = factor(cyl))) + geom_point() 
p + ylab("weight (lb)") +theme_bw()

tick labels too close to vertical axis

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

Answers (2)

Thomas K
Thomas K

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

Didzis Elferts
Didzis Elferts

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

enter image description here

Upvotes: 5

Related Questions