如何在ggplot中无需外部函数复现Base Plot的直方图分箱规则?
Replicate Base R's Sturges Binning in ggplot2 (No Extra Functions)
Got it! Let's break down how to reproduce the exact binning behavior of base R's hist() function in ggplot2, without relying on external helper functions. We'll use the classic faithful dataset as an example.
Step 1: Understand Base R's Binning Logic
Base R's hist() uses two key steps for default Sturges binning:
- It calculates the recommended number of bins with
nclass.Sturges()(this is based on the total number of observations in the dataset) - Then it uses
pretty()to generate "clean" rounded breakpoints that align with that bin count (this is why the actual bins might look slightly adjusted from a strict Sturges count—pretty()ensures breakpoints are easy to read)
Step 2: Manually Calculate the Breakpoints
We can replicate this logic directly in our workflow:
library(tidyverse) data("faithful") # Get the min and max of the waiting time variable waiting_range <- range(faithful$waiting) # Calculate the Sturges-recommended number of bins sturges_bin_count <- nclass.Sturges(faithful$waiting) # Generate the same "pretty" breakpoints base hist uses custom_breaks <- pretty(waiting_range, n = sturges_bin_count, min.n = 1)
Step 3: Plot with ggplot2 Using Custom Breaks
Now pass these custom breakpoints to geom_histogram() to match base R's output:
ggplot(faithful, aes(x = waiting)) + geom_histogram( breaks = custom_breaks, fill = "steelblue", color = "white", alpha = 0.8 ) + labs( title = "Waiting Time Between Old Faithful Eruptions", subtitle = "Matching Base R's Default Sturges Binning", x = "Waiting Time (Minutes)", y = "Frequency" ) + theme_light()
Verify the Match
To confirm this works, run hist(faithful$waiting) in your console. You'll see the bin breakpoints and overall histogram shape are identical to the ggplot version.
内容的提问来源于stack exchange,提问作者Derek Corcoran
相关产品推荐
相关产品推荐

