Mark Heckmann
Mark Heckmann

Reputation: 11441

Broken polygons in levelplot using ggplot stat_density_2d

Creating a levelplot using ggplot's stat_density_2d I get "broken" polygons. For example, the outer one in the example below.

How can I fix this, to get a smooth form?

enter image description here

set.seed(0)
n <- 50
d <- data.frame(x = rnorm(n, -.7, .5), 
                y = rnorm(n, 0, .8))
ggplot(d, aes(x, y)) + 
  geom_point() +
  stat_density_2d(aes(fill = ..level..), alpha=.1, geom = "polygon") 

Upvotes: 1

Views: 1040

Answers (1)

Weihuang Wong
Weihuang Wong

Reputation: 13138

To build on @hrbrmstr's answer (which, at least on my machine, lops off one data point because the x scale isn't sufficiently wide), a slightly more involved approach would be to get the limits of the data, set the scale limits, then reset the plot limits back to the original range:

g <- ggplot(d, aes(x, y)) + 
  geom_point() +
  stat_density_2d(aes(fill = ..level..), alpha=.1, geom = "polygon")

dat_lims <- lapply(d, function(v) c(min(v), max(v)))
plot_lims <- ggplot_build(g)$panel$ranges[[1]][c("x.range", "y.range")]

g +
  scale_x_continuous(limits = dat_lims$x * 1.1) + 
  scale_y_continuous(limits = dat_lims$y * 1.1) +
  coord_cartesian(xlim = plot_lims$x.range, ylim = plot_lims$y.range)

Output:

enter image description here

Upvotes: 5

Related Questions