Skip to content

Instantly share code, notes, and snippets.

@michael-groble
Last active August 9, 2017 20:40
Show Gist options
  • Save michael-groble/4526370 to your computer and use it in GitHub Desktop.
Save michael-groble/4526370 to your computer and use it in GitHub Desktop.
plot Chicago crime data
source('plot_crime.R')
city <- read.city_boundary('chicago/City_Boundary.shp')
crimes <- read.crimes('chicago/Crimes_-_2011.csv')
png('chicago/crimes_2011.png', width=835, height=1295)
plot_crime(crimes, city, max_rank=20, ncol=4)
dev.off()
library(maptools)
library(ggplot2)
library(plyr)
library(rgeos)
read.city_boundary <- function(file_name)
{
city <- readShapePoly(file_name)
city <- fortify(gSimplify(city, tol=100), region='OBJECTID')
rename(city, c(long="x", lat="y"))
}
read.crimes <- function(file_name)
{
crimes <- read.csv(file_name, as.is = TRUE)
crimes$Primary.Type[crimes$Primary.Type == 'INTERFERE WITH PUBLIC OFFICER'] <- 'INTERFERENCE WITH PUBLIC OFFICER'
crimes$Primary.Type[crimes$Primary.Type == 'OFFENSES INVOLVING CHILDREN'] <- 'OFFENSE INVOLVING CHILDREN'
primary_factors <-rev(arrange(count(crimes, 'Primary.Type'), freq)[,1])
crimes$Primary.Type <- factor(crimes$Primary.Type, primary_factors, ordered=TRUE)
crimes
}
no_grid_opts <- function()
{
opts(panel.grid.major=theme_blank(),
panel.grid.minor=theme_blank(),
axis.ticks=theme_blank(),
axis.text.x=theme_blank(),
axis.text.y=theme_blank(),
axis.title.x=theme_blank(),
axis.title.y=theme_blank(),
panel.background = theme_rect(fill = 'white', colour = 'grey80'))
}
plot_crime <- function(crimes, city, min_rank=1, max_rank=30, ncol=6)
{
ranks = subset(crimes, as.integer(Primary.Type) >= min_rank & as.integer(Primary.Type) <= max_rank)
ggplot(data=ranks, aes(X.Coordinate, Y.Coordinate)) +
geom_path(data=city, aes(x, y, group=group), size=.2, colour='grey80') +
geom_point(size=.2) +
facet_wrap(~ Primary.Type, ncol=ncol) +
coord_equal(ratio=1) +
no_grid_opts()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment