【发布时间】:2020-09-23 21:10:16
【问题描述】:
我正在尝试创建一个带有密度叠加的 ggplot 直方图,其中 alpha 变化超过数字 1。可以在我们的模拟部分的每个结果下看到一个示例 on 538。阿尔法根据选举人票数而有所不同。我接近得到一个类似的图表,但我不知道如何让密度和直方图一起工作。
代码
library(data.table)
library(ggplot2)
dt <- data.table(ratio = rnorm(10000, mean = .5, sd = 1))
dt[, .(ratio,
al = (ratio >= 1))] %>%
ggplot(aes(x = ratio, alpha = al)) +
geom_histogram(aes(), bins = 100,
fill = 'red') +
geom_density(aes(),size = 1.5,
color = 'blue') +
geom_vline(xintercept = 1,
color = '#0080e2',
size = 1.2) +
scale_alpha_discrete(range = c(.65, .9))
此尝试根据需要正确地将 alpha 更改为 1,但密度估计未按比例缩放。
dt[, .(ratio,
al = (ratio >= 1))] %>%
ggplot(aes(x = ratio)) +
geom_histogram(aes(y = ..density.., alpha = al), bins = 100,
fill = 'red') +
geom_density(aes(y = ..scaled..),size = 1.5,
color = 'blue',) +
geom_vline(xintercept = 1,
color = '#0080e2',
size = 1.2) +
scale_alpha_discrete(range = c(.65, .9))
这种尝试正确地缩放了密度曲线,但现在 geom_histogram 是针对低于 1 和高于 1 的值单独计算的。我希望它们作为一组计算。
我错过了什么?
【问题讨论】:
-
愿意分享
theme_josh? -
糟糕忘了删除它。它只是网格标记和传说的东西。该问题不需要