R ggmap countour plot: Convert ..level.. to events per squared area of distance
Asked Answered
D

0

3

Using the example in ggmap: Spatial Visualization with ggplot2, by David Kahle and Hadley Wickham of a filled contour plot of violent crimes (Figure 9 in the linked article), I would like to know if instead of ..level.., how I could instead show average violent crimes per square (1000) kilometers as for me this would be much easier to interpret.

Here is an extract of the code from that article:

require(ggmap)
violent_crimes <- subset(crime, offense != "auto theft" & offense != "theft" & offense != "burglary")
violent_crimes$offense <- factor(violent_crimes$offense, levels = c("robbery", "aggravated assault", "rape", "murder"))
# restrict to downtown
violent_crimes <- subset(violent_crimes, -95.39681 <= lon & lon <= -95.34188 & 29.73631 <= lat & lat <= 29.78400)

houston <- get_map("houston", zoom = 14)
HoustonMap <- ggmap(houston, legend = "topleft")
HoustonMap +
  stat_density2d(
    aes(x = lon, y = lat, fill = ..level.., alpha = ..level..),
    size = 2, data = violent_crimes,
    geom = "polygon"
  )  + guides(alpha=FALSE)

N.B. I found the links provided by @JasonAizkalns here to posts 1 and 2 useful in understanding ..level..

Defroster answered 22/1, 2016 at 4:32 Comment(2)
As far as I'm aware of, it's not possible to pass a data vector to fill in stat_density_2d. I guess the best alternative would be to overlay your data on crime events onto a regular grid of cell. That should be quite simple once you have the shapefile of the area. Do you have a link to the shapefile of Houston you could share?Afternoons
I set out to do exactly what your question asks. But then I read this and decided not to.Hagans

© 2022 - 2024 — McMap. All rights reserved.