Skip to content

Documentation for plotting bin proportion in geom_histogram #3522

Closed
@kuriwaki

Description

@kuriwaki

Showing proportions (instead of counts or density) of a bin in a histogram is a common exercise, but this is not documented. Most stackoverflow suggestions are either conflicting or outdated.

The solution below by @clauswilke in a now-locked thread seems like the best practice. Could this trick as well as the width stat be documented in the geom_histogram manual and the ggplot website?


library(ggplot2)

# instead of plotting the count statistic in geom_histogram, 
# plot the proportion of a bin, which is equivalent to the product of the 
# density and the width statistic
ggplot(diamonds, aes(x = carat, y = stat(density*width))) +
  geom_histogram(binwidth = 0.01)

Created on 2019-09-07 by the reprex package (v0.3.0)

The solution is to use aes(y = stat(width*density)). This converts the density back into a percentage. Reprex follows below.

Originally posted by @clauswilke in #2499 (comment)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions