Skip to content

Instantly share code, notes, and snippets.

@alexeyknorre
Last active October 17, 2019 18:30
Show Gist options
  • Save alexeyknorre/8a9dd6a02a878ad3ee3c01ea288280fe to your computer and use it in GitHub Desktop.
Save alexeyknorre/8a9dd6a02a878ad3ee3c01ea288280fe to your computer and use it in GitHub Desktop.
West Philly crime heatmap code in R
library(data.table)
library(lubridate)
library(dplyr)
library(ggmap)
# Data: https://www.opendataphilly.org/dataset/crime-incidents
philly <- fread("data/incidents.csv",
select = c("location_block","text_general_code","dispatch_time","dispatch_date", "lat","lng"))
# Create variable with year
philly$year <- year(philly$dispatch_date)
# Subset incidents in West Philly / University City
philly_subset <- philly[philly$lat < 39.966 & philly$lat > 39.942 & philly$lng > -75.25 & philly$lng < -75.19,]
philly_subset %>%
# Subsetting
filter(text_general_code %in% c("Other Assaults",
"Aggravated Assault No Firearm",
"Robbery Firearm")) %>%
# Plotting
qmplot(lng, lat, data = ., geom = "blank",
zoom = 15, maptype = "toner", darken = 0.1, legend = "topright") +
stat_density_2d(aes(fill = ..level..), geom = "polygon", alpha = .3, color = NA) +
scale_fill_gradient2("Assault and Robbery\nIncidents in 2018:", low = "green", mid = "yellow", high = "red", midpoint = 1000) +
theme(legend.position="none")
ggsave(filename = "west-philly-uc-2018-crime-map.png",width = 10, height = 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment