如何在ggplot图中绘制y和x轴的刻度和数字?

6

我正在使用ggplot绘制图表。这是使用ggplot包的示例:

df <- data.frame(
  gp = factor(rep(letters[1:3], each = 10)),
  y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))

ggplot(df, aes(gp, y)) +
  geom_point() +
  geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
  theme(    axis.text.y = element_text(hjust = 3),
            axis.text.x = element_text(vjust = 5),
            axis.ticks.length = unit(-0.25,
                                     "cm"), # length of the axis ticks

  )

这里是输出:

enter image description here

正如您所看到的,刻度线位于内部,但y轴上的数字对齐得很糟糕,而x轴上的数字则重叠在刻度线上。
因此,最终我希望刻度线在图表内部,坐标轴标签(数字)在ggplot图表内部。我听说应该使用边距工具,但我不确定如何指定图表内部的边距。
编辑:您可以看到,在使用margin函数时,数字的对齐方式不正确... enter image description here

这是一个好问题,但我必须说,如果刻度标记在图形外面,这看起来不会更丑吗? - InfiniteFlash
1
在这个例子中是的。这是为另一个项目!不用担心,它可以看起来很好!特别是在地图上! - M. Beausoleil
1
好的,我不会再怀疑你了 ;) - InfiniteFlash
1个回答

6
也许你正在寻找在element_text中使用margin函数来指定margin的方法?
ggplot(df, aes(gp, y)) +
  geom_point() +
  geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
  theme(    axis.text.y = element_text(margin = margin(0,-.5,0,.5, unit = 'cm')),
            axis.text.x = element_text(vjust = 5, margin = margin(-0.5,0,0.5,0, unit = 'cm')),
            axis.ticks.length = unit(-0.25,
                                     "cm") , # length of the axis ticks

  ) + ylim(c(min(df$y)-.5,max(df$y)))

enter image description here


我尝试过了,但ylab的数字没有对齐。请参见我帖子中的编辑。 - M. Beausoleil
1
对不起,我错过了问题的那一部分。我已经进行了编辑以解决它。我认为你只需要在axis.text.y的element_text中再次调用margin。 - jrlewi
1
@lewisjr2 我建议您附上您的结果图片。 - InfiniteFlash
好的观点 - 感谢@InfiniteFlashChess。请注意,我还有一个调用ylim的操作,以确保您的数据点不会覆盖标签。 - jrlewi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接