考虑以下
d <- read.table(text="
class num married type
1 0.0 63530 23067 A
2 2.5 27061 16601 A
3 3.5 29938 19332 B
4 4.5 33076 24112 A
5 5.6 45759 32405 A
6 6.5 72794 61234 A
7 8.0 153177 107089 A
8 10.8 362124 267303 A
9 13.5 551051 334578 A
10 15.5 198634 181530 A
11 2.5 52710 10450 B
12 7.0 123177 98076 B
13 8.0 262524 105331 B
14 13.5 301031 127690 B
15 15.5 103634 49887 B
")
p <- ggplot(d) +
geom_histogram(aes(x=class,weight=num,fill=type),
binwidth=6,alpha=.4) +
geom_histogram(aes(x=class,weight=married,fill=type,position = "identity"),
binwidth=6) +
facet_grid(~type)
这接近我所需要的。但是,对我来说,拥有可变 binwidth的直方图会更好,事实证明这比我预期的要困难。比如我把脚本改成如下
bins <- c(0,4,8,16)
p <- ggplot(d) +
geom_histogram(aes(x=class,weight=num,fill=type),
breaks = bins,alpha=.4) +
geom_histogram(aes(x=class,weight=married,fill=type,position = "identity"),
breaks = bins) +
facet_grid(~type)
但在这种情况下,条形图已正确缩放 - 即条形面积,而不是条形长度,分别与num
和成正比married
。请注意,添加y =..density..
并不能解决问题,因为在这种情况下,直方图不会根据数量进行缩放。有什么建议吗?