How to avoid contour closure errors with stat_density_2d?

Any suggestions on how to avoid the contour closure errors as seen in the first plot below? Looks to me like it's being caused by the geom, alpha and/or fill elements.

library(ggplot2)
library(magrittr)

u <- svd(iris[-5]) %$%
    {
        data.frame(x = u[, 1], y = u[, 2])
    }

ggplot() +
    stat_density_2d(data = u,
                    aes(x, y,
                        alpha = ..level..,
                        fill = ..level..),
                    geom = "polygon")


ggplot() +
    stat_density_2d(data = u,
                    aes(x, y))

Created on 2019-07-19 by the reprex package (v0.3.0)

Just expand the limits of your axes - for example thusly:

library(ggplot2)
library(magrittr)

u <- svd(iris[-5]) %$%
  {
    data.frame(x = u[, 1], y = u[, 2])
  }

ggplot() +
  stat_density_2d(data = u,
                  aes(x, y,
                      alpha = ..level..,
                      fill = ..level..),
                  geom = "polygon") +
  scale_x_continuous(limits = c(-.12, -.04)) +
  scale_y_continuous(limits = c(-.15, .2))

4 Likes

Ah, smashing. Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.