调整 ggplot2 geom_density() 中的 xlim() 以模仿 ggvis layer_densities() 行为

Adjusting x limits xlim() in ggplot2 geom_density() to mimic ggvis layer_densities() behavior

有没有办法让 ggplot2 的 geom_density() 函数模仿 ggvis 的 layer_densities() 的行为?也就是说,在不调用 xlim() 的情况下,让 p1 看起来像 p3(见下文)?具体来说,我更喜欢平滑密度曲线尾部的视图。

library(ggvis)
library(ggplot2)

faithful %>% 
  ggvis(~waiting) %>% 
  layer_densities(fill := "green") -> p1

ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) -> p2

ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) +
  xlim(c(30, 110)) -> p3

p1
p2
p3

ggvis 输出:

ggplot2 "default":

ggplot2 "desired":

注意:可以通过以下方式让 ggvis 模仿 ggplot2(使用 trim=TRUE),但我想走另一个方向...

faithful %>% 
  compute_density(~waiting, trim=TRUE) %>% 
  ggvis(~pred_, ~resp_) %>% 
  layer_lines()

如何调用 xlim,但有以编程方式定义的限制?

l <- density(faithful$waiting)
ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) +
  xlim(range(l$x))

虽然缺点是密度估计是双倍的,所以请记住这一点。