[英]Kernel density plot bandwidth in ggplot2 with `facet_wrap`
I would like to use stat_density()
and facet_wrap()
in the ggplot2
package to create kernel density plots for different groupings, but I want to make sure that I use the same bandwidth for every plot. 我可以确定stat_density()
对每个 plot 使用相同的带宽吗?
例如,使用diamonds
:
library(ggplot2)
ggplot(diamonds, aes(x = carat)) +
stat_density() +
facet_wrap(~ cut) +
scale_x_log()
在文档中它显示我可以使用adjust
来调整自动带宽,但这只是应用倍数并将我返回到原始问题。 stat_density()
也有一个...
选项,但我无法通过density()
选项bw
,如下所示:
ggplot(diamonds, aes(x = carat)) +
stat_density(bw = 1) +
facet_wrap(~ cut) +
scale_x_log()
所以,如果stat_density()
没有在所有方面使用相同的带宽,有没有办法可以强制这样做? 我尝试了带有transform()
和density()
的ddply()
解决方案,但这失败了,因为density()
不一定返回与输入相同数量的 x 和 y 值。 有任何想法吗? 谢谢!
编辑看起来ggplot2
为每个方面分配了最佳带宽(看起来@Ramnath 和 Dianardo、Fortin 和 Lemieux Econometrica 1996 同意这一点),而不是我正在寻求的恒定带宽。 但是,如果我确实想要所有方面的带宽恒定,那么我在下面的尝试会失败。
my.density <- function(x) {
temp <- density(x$carat, bw = 0.5)
return(data.frame(carat = temp$x, density = temp$y))
}
temp <- ddply(diamonds, .(cut), my.density)
ggplot(temp, aes(x = carat, y = density)) +
geom_point() +
facet_wrap(~ cut) +
scale_x_log()
Warning messages:
1: In match.fun(get(".transform", .))(values) : NaNs produced
2: In match.fun(get(".transform", .))(values) : NaNs produced
3: In match.fun(get(".transform", .))(values) : NaNs produced
4: In match.fun(get(".transform", .))(values) : NaNs produced
5: In match.fun(get(".transform", .))(values) : NaNs produced
6: Removed 84 rows containing missing values (geom_point).
7: Removed 113 rows containing missing values (geom_point).
8: Removed 98 rows containing missing values (geom_point).
9: Removed 98 rows containing missing values (geom_point).
10: Removed 106 rows containing missing values (geom_point).
警告是由于my.density
中carat
的负值。 对您的代码稍作修改就可以解决问题:
ggplot(temp, aes(x = carat, y = density)) +
geom_line(subset = .(carat > 0)) +
facet_wrap(~ cut) + scale_x_log()
希望这是有用的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.