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

Is there a way to get ggplot2 geom_density() mimic the behavior of ggvis layer_densities() ? That is, make p1 look like p3 (see below) without calling xlim() ? In particular, I prefer a view that smooths the tails of the density curve.

 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 Output: p1

ggplot2 "default": p2

ggplot2 "desirable": p3

Note. You can make ggvis mimic ggplot2 as follows: (using trim=TRUE ), but I would like to go in a different direction ...

 faithful %>% compute_density(~waiting, trim=TRUE) %>% ggvis(~pred_, ~resp_) %>% layer_lines() 
+5
source share
1 answer

What about calling xlim , but with limitations that are programmatically defined?

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

enter image description here

The disadvantage is a double density estimate, so keep that in mind.

+6
source

Source: https://habr.com/ru/post/1214084/


All Articles