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

问题描述 投票:5回答:1

我正在使用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图中的轴标签(数字)。我听说我们应该使用保证金工具,但我不确定如何在图表中指定边距。

编辑:您可以看到如何使用保证金功能,数字未正确对齐... enter image description here

r plot ggplot2 axis
1个回答
5
投票

也许使用margin函数在element_text中指定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

© www.soinside.com 2019 - 2024. All rights reserved.