如何用ggplot2在R中绘制与lattice一致的相对频率直方图?
Solution: Match Lattice's Relative Frequency Histogram with ggplot2
Let's fix your code step by step—here's why your original attempt didn't work, and how to adjust it:
1. Why your initial ggplot2 code failed
- You used
geom_bar()which is designed for discrete categorical data, but your variableais continuous (generated withrunif()). For continuous data, we needgeom_histogram()to automatically create bins and calculate frequencies. - The
..prop..statistic calculates proportions within each group. Without specifying a group, ggplot treats each bin as its own group, so every bin shows a proportion of 100%—that's why your plot looked wrong.
2. Correct code to replicate the lattice histogram
We'll use geom_histogram() and either calculate relative frequencies directly from ..count.., or fix the ..prop.. calculation by setting a global group:
Option 1: Calculate relative frequency with ..count../sum(..count..)
library(ggplot2) library(scales) # For percent labels a <- runif(100) dt <- data.frame(a) ggplot(dt, aes(x = a)) + # Calculate relative frequency as bin count / total observations geom_histogram(aes(y = ..count../sum(..count..)), bins = 10) + scale_y_continuous(labels = percent)
Option 2: Use ..prop.. with group = 1
Setting group = 1 tells ggplot to calculate proportions across the entire dataset instead of per bin:
library(ggplot2) library(scales) a <- runif(100) dt <- data.frame(a) ggplot(dt, aes(x = a, group = 1)) + geom_histogram(aes(y = ..prop..), bins = 10) + scale_y_continuous(labels = percent)
3. Match Lattice's binning
Lattice's histogram() uses 10 bins by default, so we set bins = 10 in geom_histogram() to get identical bin breaks to your original lattice plot.
内容的提问来源于stack exchange,提问作者neringab
相关产品推荐
相关产品推荐

