stat_summary_bin 在 x 轴刻度处

stat_summary_bin at x-axis ticks

如何让 ggplot 的 stat_summary_bin 在指定的 x 轴值处进行汇总?例如,在下面的图中,我希望摘要位于 x=-1、0、1、2 等位置。现在它位于 -1.5、-0.5、0.5 和 1.5。

df = data.frame(x=rnorm(1000), y=rnorm(1000))
ggplot(df, aes(x=x, y=y)) +
stat_summary_bin(binwidth=1)

这是 ggplot2 中的一个已知错误,仅在 late July 中得到修复。解决方法,来自错误报告:

df <- data.frame(x = rnorm(1000), y = rnorm(1000))
ggplot(df, aes(x = cut_width(x, 1, center = 0), y = y)) +
  stat_summary_bin(binwidth = 1)

并且,要固定 x 轴:

ggplot(df, aes(x = cut_width(x, 1, center = 0), y = y)) +
  stat_summary_bin(binwidth = 1) +
  scale_x_discrete(labels = -3:3, name = 'x')

breaks 参数将在下一个版本的 ggplot2 中可用,应该会在接下来的几周内发布。

如果你现在想 运行 ggplot2 的开发版本,你应该可以通过:

devtools::install_github("tidyverse/ggplot2")