paleolimbot / ggspatial

Enhancing spatial visualization in ggplot2
https://paleolimbot.github.io/ggspatial
368 stars 34 forks source link

Planned support for dot density ggplot layers? #79

Open JosiahParry opened 3 years ago

JosiahParry commented 3 years ago

Heya! One type of plot I've been trying to figure out how to make w ggplot2 is a dot density map from a polygon and some z value. Is this on your radar?

paleolimbot commented 3 years ago

Maybe! Is this more or less what you were looking for? (the bottom bit is for me, later, because it's along the lines of how I'd implement this except it doesn't work yet)

library(ggplot2)
library(ggspatial)

xy <- data.frame(lon = rnorm(100, sd = 20), lat = rnorm(100, sd = 20))

ggplot(xy, aes(lon, lat)) +
  geom_density2d()


StatSpatialDensity <- ggspatial:::create_spatial_stat_class(ggplot2::StatDensity2d, "stat_spatial_density")

stat_spatial_density <- function(
  mapping = NULL, data = NULL, crs = NULL, geom = "path",
  position = "identity", ..., show.legend = NA, inherit.aes = TRUE
) {
  ggplot2::layer(
    data = data, mapping = mapping, stat = StatSpatialDensity,
    geom = geom, position = position, show.legend = show.legend,
    inherit.aes = inherit.aes, params = list(na.rm = FALSE, crs = crs, ...)
  )
}

ggplot(xy, aes(lon, lat)) +
  annotation_map_tile(progress = "none") +
  geom_spatial_point() +
  stat_spatial_density()
#> Assuming `crs = 4326` in stat_spatial_identity()
#> Assuming `crs = 4326` in stat_spatial_density()

Created on 2021-01-21 by the reprex package (v0.3.0)