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

时间:2023-02-01 23:57:34

I'm plotting a graph using ggplot. Here is the exemple with the ggplot package:

我正在使用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

  )

Here is the output:

这是输出:

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

As you can see, the ticks are inside but the numbers for the y axis are terribly aligned and the ones on the X axis are overlapping the ticks.

如您所见,刻度线在内部,但y轴的数字非常对齐,而X轴上的数字与刻度线重叠。

So in the end I'd want the ticks inside the graph and the axis labels (the numbers) inside the ggplot graph. I've heard that we should use the margin tool, but I'm not sure how to specify margins inside the graph.

所以最后我想要图中的刻度和ggplot图中的轴标签(数字)。我听说我们应该使用保证金工具,但我不确定如何在图表中指定边距。

Edit: You can see how when using the margin function, the numbers are not aligned properly... 如何在ggplot图中绘制y和x轴的刻度和数字?

编辑:您可以看到在使用保证金功能时,数字未正确对齐...

1 个解决方案

#1


5  

Maybe specifying margin within element_text using the margin function is what you are looking for?

也许您正在寻找使用保证金功能在element_text中指定保证金?

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

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

#1


5  

Maybe specifying margin within element_text using the margin function is what you are looking for?

也许您正在寻找使用保证金功能在element_text中指定保证金?

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

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