Jonas Lindeløv
Jonas Lindeløv

Reputation: 5683

stat_summary_bin at x-axis ticks

How do I make ggplot's stat_summary_bin do the summaries at specified x-axis values? For example, in the plot below I'd like the summaries at x=-1, 0, 1, 2, etc. Now it's at -1.5, -0.5, 0.5, and 1.5.

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

enter image description here

Upvotes: 1

Views: 403

Answers (1)

Claus Wilke
Claus Wilke

Reputation: 17790

This is a known bug in ggplot2 that was only fixed in late July. A workaround, from the bug report:

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)

enter image description here

And, to fix the x axis:

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

enter image description here

The breaks argument will be available in the next version of ggplot2, which should be released within the next few weeks.

If you want to run the development version of ggplot2 now, you should be able to do so via:

devtools::install_github("tidyverse/ggplot2")

Upvotes: 2

Related Questions