如何将刻度标签移近轴?

时间:2015-09-29 06:01:26

标签: 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

我想将5000,4000,3000和2000移近垂直轴。我知道可以使用theme(axis.title.y=element_text(vjust=0.36,hjust=.36))或类似的方法来移动轴标题,但有时我真的想要移动刻度标签,而不是轴标题。

2 个答案:

答案 0 :(得分:6)

版本2.0.0引入了我们可以在此处使用的新margin()

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

我对此issue on github的解读是,vjust仅针对y-axishjust使用x-axis。要更改刻度标签和轴之间的距离,请在y轴上使用margin(r = x),在margin(t = x)上使用x-axiselement_text的文档内容为:&#34;创建主题时,边距应放在文本的一侧,面向图的中心。&#34;

答案 1 :(得分:5)

一种解决方案是使用axis.ticks.margin=的{​​{1}}元素并将其设置为0.但这会影响两个轴。

theme()

enter image description here