Heidi
Heidi

Reputation: 187

Changing xlim automatically changes ylim for geom_density

I think my problem is best explained by an example:

set.seed(12)
n <- 100
x <- rt(n, 1, 0)

library("ggplot2")
p <- ggplot() + geom_density(aes(x))
p
p + xlim(min(x), 300)

default xlim

new xlim

Why does the y axis automatically change when I change xlim? The density should not change, so it does not make sense to me. When I use base plot this does not happen.

plot(density(x))
plot(density(x), xlim = c(min(x), 300)) 

Upvotes: 4

Views: 2160

Answers (2)

Lasse Kliemann
Lasse Kliemann

Reputation: 289

Use geom_density(..., n=2^16) or similar for a more stable experience.

It would appear that in contrast to density, the function geom_density does take the x range set via xlim into account when deciding at which points to evaluate the density estimation. However, the number of such points remains fixed at 512 (unless using n to set it to a higher value). Hence the larger the x range, the more likely some peaks will be missed. I think this should be documented.

Upvotes: 1

eminik
eminik

Reputation: 145

Using xlim completely drops observations that are outside of the range. Try using p + coord_cartesian(xlim = c(min(x), 300)).

Upvotes: 4

Related Questions