Crime in the Peak District - what is happening?

Setup R Environment Packages

# Load packages https://github.com/njtierney/ukpolice
library(ukpolice)
library(leaflet)
library(htmltools)
library(ggplot2)
library(dplyr)

Create a function to query API

# month character variable ISO Date YYYY-MM
mn <- c("2019-01", "2019-02", "2019-03", "2019-04", "2019-05", "2019-06",
        "2019-07", "2019-08", "2019-09", "2019-10", "2019-11", "2019-12")

Access https://data.police.uk/ (use 2019 as complete year - “2020-10” is latest API data).

pdnp_df <- function(mn){
  all_crime_df <- data.frame()
  for (i in mn){
    crime_poly <- ukc_street_crime(
      lat = c(53.033956, 53.596922, 53.596922, 53.033956),
      lng = c(-1.511089, -1.511089, -2.107609, -2.107609),
      date = i
    )
    all_crime_df <- rbind(all_crime_df, crime_poly)
  }
  return(all_crime_df)
}

crime_poly <- pdnp_df(mn)

Convert the vector to numeric

crime_poly$longitude <- as.numeric(crime_poly$longitude)
crime_poly$latitude <- as.numeric(crime_poly$latitude)

Create labels for the leaflet map

labels <- paste0(
  "<strong>Category:</strong> ", crime_poly$category,"</br>",
  "<strong>Street Description:</strong>  ", crime_poly$street_name
) %>% lapply(htmltools::HTML)

Create the leaflet map widget

map <- leaflet(options=leafletOptions(
  maxBounds = list(list(53.033,-1.511), list(53.596,-2.107)), minZoom = 7)) %>%
  addTiles() %>% 
  addCircleMarkers(lng = crime_poly$longitude, 
                   lat = crime_poly$latitude,
                   popup = labels,
                   clusterOptions = markerClusterOptions())
map

Data Exploration

Lets take a very quick gander :)

# create a numeric vector
crime_poly$instance <- 1

What are the levels and types of crime?

Bar Chart of total instances of crimes by crime category

ggplot(crime_poly, aes(x=category, y=instance, fill=category)) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle = 90))

When are these crime occuring (by month)?

Faceted Heat Map

police_grid <- crime_poly %>%
  unique() %>%
  group_by(category, month) %>%
  summarise(instance = n())

ggplot(police_grid, aes(x=month, y=category, fill=instance)) +
  geom_tile(colour="white",size=0.25)+
  scale_fill_distiller(name="Number of crimes",
                      palette = "Spectral") +
  geom_tile() + theme(axis.text.x = element_text(angle = 90))

tbc… :)