Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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.

like image 466
Alex Holcombe Avatar asked Sep 29 '15 06:09

Alex Holcombe


People also ask

How do I move the axis ticks in Excel?

On the Format tab, in the Current Selection group, click Format Selection. In the Axis Options panel, under Tick Marks, do one or more of the following: To change the display of major tick marks, in the Major tick mark type box, click the tick mark position that you want.

How do I move axis labels in R?

Key ggplot2 R functionsp + xlab(“New X axis label”): Change the X axis label. p + ylab(“New Y axis label”): Change the Y axis label. p + labs(x = “New X axis label”, y = “New Y axis label”): Change both x and y axis labels.

What is an axis tick mark?

A tick is a short line on an axis. For category axes, ticks separate each category. For value axes, ticks mark the major divisions and show the exact point on an axis that the axis label defines. Ticks are always the same color and line style as the axis. Ticks come in two types: major and minor.


1 Answers

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

like image 131
Thomas K Avatar answered Sep 27 '22 02:09

Thomas K