You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 variable a is continuous (generated with runif()). For continuous data, we need geom_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:43:11