Skip to content

Conversation

mattansb
Copy link
Contributor

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

Copy link
Collaborator

@teunbrand teunbrand left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for submitting a PR to fix this! This mostly looks great, I'd just like to move a small part for clarity.

@mattansb
Copy link
Contributor Author

@teunbrand I think that's all of it!

Copy link
Collaborator

@teunbrand teunbrand left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lovely, looks great! Thank you for the contribution

@mattansb
Copy link
Contributor Author

Thank you!

@teunbrand teunbrand merged commit f12b73d into tidyverse:main Oct 25, 2024
13 checks passed
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.

2 participants