Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

ggvis

Is there a way to make ggplot2's geom_density() function mimic the behavior of ggvis's layer_densities()? That is, make it so p1 looks like p3 (see below) without the call to xlim()? Specifically, I prefer the 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 "desired": p3

Note: One can make ggvis mimic ggplot2 via the following (using trim=TRUE), but I would like to go the other direction...

faithful %>% 
  compute_density(~waiting, trim=TRUE) %>% 
  ggvis(~pred_, ~resp_) %>% 
  layer_lines()
like image 563
JasonAizkalns Avatar asked Feb 24 '15 14:02

JasonAizkalns


1 Answers

How about calling xlim, but with limits that are defined programmatically?

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 downside is double density estimation though, so keep that in mind.

like image 200
tonytonov Avatar answered Nov 07 '22 10:11

tonytonov