Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand on docs/example for cases with non-equal-width bins in stat_bin() #6151

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mattansb
Copy link

This PR addresses the points brought up in #5895:

  • The default behavior of stat_bin() of mapping counts to height instead of area is suitable for most common applications.
  • This is because most common applications use equal-width bins.
  • When non-equal-width bins are used, this behavior produces histograms that are hard to interpret and violate the proportional ink principle.
  • Therefore, I suggested adding to the docs/examples something that discusses this / shows how to do it properly.

Which is what I did

The Changes

1. Slightly expanded the Computed variables bullet for width.

Previously was:

  • after_stat(width)
    widths of bins.

Now is:

  • after_stat(width)
    widths of bins. Use with after_stat(count / width) to obtain bars with areas representing counts (e.g., with non-equal-width bins). See example.

2. Added an example

# When using the non-equal-width bins, we need to set the area of the bars to
# represent the counts (not the height).
# Here we're using 10 equi-probable bins:
price_bins <- quantile(diamonds$price, probs = seq(0, 1, length = 11))

ggplot(diamonds, aes(price)) +
  geom_histogram(breaks = price_bins, color = "black") # wrong (height = count)

ggplot(diamonds, aes(price, after_stat(count / width))) +
  geom_histogram(breaks = price_bins, color = "black") # area = count

Created on 2024-10-21 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant