Sebastian
Sebastian

Reputation: 939

ggplot does not display density curve correctly when changing xlim and ylim

Consider the following plot:

library(ggplot2)
dat <- data.frame(x = rnorm(1e6, sd = 0.01))
ggplot(data = dat, aes(x = x)) + geom_density() + ylim(0, 1) + xlim(-5, 5)

enter image description here

A considerable part of the density-curve for ~ density > 0.2 is missing.

Does anyone know a workaround?

Upvotes: 0

Views: 294

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174278

You have to use coord_cartesian to keep all the underlying data points:

library(ggplot2)
dat <- data.frame(x = rnorm(1e6, sd = 0.01))
ggplot(data = dat, aes(x = x)) + geom_density() +
  coord_cartesian(xlim = c(-5, 5), ylim = c(0, 1)) 

Created on 2020-04-27 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions