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

标签 r plot ggplot2 axis

我正在使用 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 Axis 的数字非常对齐,而 X Axis 上的数字与刻度重叠。

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

编辑:您可以看到在使用边距功能时,数字未正确对齐...
enter image description here

最佳答案

也许指定 marginelement_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

关于r - 如何在ggplot图中绘制y轴和x轴的刻度和数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014329/

相关文章:

r - 绘图问题 - 图例栏比例、中断、图例、小数

R不一致: why add=T sometimes works and sometimes not in the plot() function?

r - 通过 ggplot2 中的列组合分面图

r - 将仅出现一次的值分组到其他字段中

r - 如何在没有特定日期且不超过 24 小时的情况下使用 lubridate 添加小时数?

r - `cor`中不排除NA值

matlab - 带有两个 y Axis 的条形图

r - 在ggplot中绘制这个。在一个范围内控制 y 轴线

r - 如何绘制带有嵌套类别轴的图表?

R:将列表中的每个数据帧与数据帧中的不同列合并