by Max Woolf
This notebook is the complement to my blog posts Analyzing San Francisco Crime Data to Determine When Arrests Frequently Occur and Mapping Where Arrests Frequently Occur in San Francisco Using Crime Data.
This notebook is licensed under the MIT License. If you use the code or data visualization designs contained within this notebook, it would be greatly appreciated if proper attribution is given back to this notebook and/or myself. Thanks! :)
In [1]:
options(warn = -1)
# IMPORTANT: This assumes that all packages in "Rstart.R" are installed,
# and the fonts "Source Sans Pro" and "Open Sans Condensed Bold" are installed
# via extrafont. If ggplot2 charts fail to render, you may need to change/remove the theme call.
source("Rstart.R")
library(ggmap)
options(repr.plot.mimetypes = 'image/png', repr.plot.width = 4, repr.plot.height = 3, repr.plot.res = 300)
sessionInfo()
Out[1]:
In [2]:
path <- "~/Downloads/SFPD_Incidents_-_from_1_January_2003.csv"
df <- read_csv(path)
In [3]:
df %>% head(10)
sprintf("# of Rows in Dataframe: %s", nrow(df))
sprintf("Dataframe Size: %s", format(object.size(df), units = "MB"))
Out[3]:
Out[3]:
Out[3]:
In [4]:
columns = c("Category", "Descript", "DayOfWeek", "Date", "Time", "PdDistrict", "Resolution", "X", "Y")
# select() requires column indices, so use which() to find them
df <- df %>% select(which(names(df) %in% columns))
df %>% head(10)
sprintf("# of Rows in Dataframe: %s", nrow(df))
sprintf("Dataframe Size: %s", format(object.size(df), units = "MB"))
Out[4]:
Out[4]:
Out[4]:
The All-Caps text is ugly: let's force the text in the appropriate columns into proper case. (see this Stack Overflow question)
In [5]:
proper_case <- function(x) {
return (gsub("\\b([A-Z])([A-Z]+)", "\\U\\1\\L\\2" , x, perl = TRUE))
}
df <- df %>% mutate(Category = proper_case(Category),
Descript = proper_case(Descript),
PdDistrict = proper_case(PdDistrict),
Resolution = proper_case(Resolution))
df %>% head(10)
Out[5]:
In [6]:
# grepl() is the best way to do in-text search
df_arrest <- df %>% filter(grepl("Arrest", Resolution))
df_arrest %>% head(10)
sprintf("# of Rows in Dataframe: %s", nrow(df_arrest))
sprintf("Dataframe Size: %s", format(object.size(df_arrest), units = "MB"))
Out[6]:
Out[6]:
Out[6]:
In [7]:
df_arrest_daily <- df_arrest %>%
mutate(Date = as.Date(Date, "%m/%d/%Y")) %>%
group_by(Date) %>%
summarize(count = n()) %>%
arrange(Date)
df_arrest_daily %>% head(10)
Out[7]:
In [8]:
plot <- ggplot(df_arrest_daily, aes(x = Date, y = count)) +
geom_line(color = "#F2CA27", size = 0.1) +
geom_smooth(color = "#1A1A1A") +
fte_theme() +
scale_x_date(breaks = date_breaks("2 years"), labels = date_format("%Y")) +
labs(x = "Date of Arrest", y = "# of Police Arrests", title = "Daily Police Arrests in San Francisco from 2003 – 2015")
max_save(plot, "sf-arrest-when-1", "SF OpenData")
In [9]:
# Returns the numeric hour component of a string formatted "HH:MM", e.g. "09:40" input returns 9
get_hour <- function(x) {
return (as.numeric(strsplit(x,":")[[1]][1]))
}
df_arrest_time <- df_arrest %>%
mutate(Hour = sapply(Time, get_hour)) %>%
group_by(DayOfWeek, Hour) %>%
summarize(count = n())
df_arrest_time %>% head(10)
Out[9]:
Reorder and format Factors.
In [10]:
dow_format <- c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
hour_format <- c(paste(c(12,1:11),"AM"), paste(c(12,1:11),"PM"))
df_arrest_time$DayOfWeek <- factor(df_arrest_time$DayOfWeek, level = rev(dow_format))
df_arrest_time$Hour <- factor(df_arrest_time$Hour, level = 0:23, label = hour_format)
df_arrest_time %>% head(10)
Out[10]:
In [11]:
plot <- ggplot(df_arrest_time, aes(x = Hour, y = DayOfWeek, fill = count)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6), legend.title = element_blank(), legend.position="top", legend.direction="horizontal", legend.key.width=unit(2, "cm"), legend.key.height=unit(0.25, "cm"), legend.margin=unit(-0.5,"cm"), panel.margin=element_blank()) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "# of Police Arrests in San Francisco from 2003 – 2015, by Time of Arrest") +
scale_fill_gradient(low = "white", high = "#27AE60", labels = comma)
max_save(plot, "sf-arrest-when-2", "SF OpenData", w=6)
Hmm, why is there a surge on Wednesday afternoon, and at 4-5PM on all days? Let's look at subgroups to verify there isn't a latent factor.
In [12]:
df_top_crimes <- df_arrest %>%
group_by(Category) %>%
summarize(count = n()) %>%
arrange(desc(count))
df_top_crimes %>% head(20)
Out[12]:
In [13]:
df_arrest_time_crime <- df_arrest %>%
filter(Category %in% df_top_crimes$Category[2:19]) %>%
mutate(Hour = sapply(Time, get_hour)) %>%
group_by(Category, DayOfWeek, Hour) %>%
summarize(count = n())
df_arrest_time_crime$DayOfWeek <- factor(df_arrest_time_crime$DayOfWeek, level = rev(dow_format))
df_arrest_time_crime$Hour <- factor(df_arrest_time_crime$Hour, level = 0:23, label = hour_format)
df_arrest_time_crime %>% head(10)
Out[13]:
In [14]:
plot <- ggplot(df_arrest_time_crime, aes(x = Hour, y = DayOfWeek, fill = count)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6, size = 4)) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "# of Police Arrests in San Francisco from 2003 – 2015, by Category and Time of Arrest") +
scale_fill_gradient(low = "white", high = "#2980B9") +
facet_wrap(~ Category, nrow = 6)
max_save(plot, "sf-arrest-when-3", "SF OpenData", w = 6, h = 8, tall = T)
Good, but the gradients aren't helpful because they are not normalized. We need to normalize the range on each facet. (unfortunately, this makes the value of the gradient unhelpful)
In [15]:
df_arrest_time_crime <- df_arrest_time_crime %>%
group_by(Category) %>%
mutate(norm = count/sum(count))
df_arrest_time_crime %>% head(10)
Out[15]:
In [16]:
plot <- ggplot(df_arrest_time_crime, aes(x = Hour, y = DayOfWeek, fill = norm)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6, size = 4)) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "Police Arrests in San Francisco from 2003 – 2015 by Time of Arrest, Normalized by Type of Crime") +
scale_fill_gradient(low = "white", high = "#2980B9") +
facet_wrap(~ Category, nrow = 6)
max_save(plot, "sf-arrest-when-4", "SF OpenData", w = 6, h = 8, tall = T)
Much more helpful.
In [17]:
df_arrest_time_district <- df_arrest %>%
mutate(Hour = sapply(Time, get_hour)) %>%
group_by(PdDistrict, DayOfWeek, Hour) %>%
summarize(count = n()) %>%
group_by(PdDistrict) %>%
mutate(norm = count/sum(count))
df_arrest_time_district$DayOfWeek <- factor(df_arrest_time_district$DayOfWeek, level = rev(dow_format))
df_arrest_time_district$Hour <- factor(df_arrest_time_district$Hour, level = 0:23, label = hour_format)
df_arrest_time_district %>% head(10)
Out[17]:
In [18]:
plot <- ggplot(df_arrest_time_district, aes(x = Hour, y = DayOfWeek, fill = norm)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6, size = 4)) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "Police Arrests in San Francisco from 2003 – 2015 by Time of Arrest, Normalized by Station") +
scale_fill_gradient(low = "white", high = "#8E44AD") +
facet_wrap(~ PdDistrict, nrow = 5)
max_save(plot, "sf-arrest-when-5", "SF OpenData", w = 6, h = 8, tall = T)
Not helpful either. Meh.
In [19]:
df_arrest_time_month <- df_arrest %>%
mutate(Month = format(as.Date(Date, "%m/%d/%Y"), "%B"), Hour = sapply(Time, get_hour)) %>%
group_by(Month, DayOfWeek, Hour) %>%
summarize(count = n()) %>%
group_by(Month) %>%
mutate(norm = count/sum(count))
df_arrest_time_month$DayOfWeek <- factor(df_arrest_time_month$DayOfWeek, level = rev(dow_format))
df_arrest_time_month$Hour <- factor(df_arrest_time_month$Hour, level = 0:23, label = hour_format)
df_arrest_time_month %>% head(10)
Out[19]:
In [20]:
# Set order of month facets by chronological order instead of alphabetical
df_arrest_time_month$Month <- factor(df_arrest_time_month$Month,
level = c("January","February","March","April","May","June","July","August","September","October","November","December"))
plot <- ggplot(df_arrest_time_month, aes(x = Hour, y = DayOfWeek, fill = norm)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6, size = 4)) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "Police Arrests in San Francisco from 2003 – 2015 by Time of Arrest, Normalized by Month") +
scale_fill_gradient(low = "white", high = "#E74C3C") +
facet_wrap(~ Month, nrow = 4)
max_save(plot, "sf-arrest-when-6", "SF OpenData", w = 6, h = 6, tall = T)
That is not helpful either!
In [21]:
df_arrest_time_year <- df_arrest %>%
mutate(Year = format(as.Date(Date, "%m/%d/%Y"), "%Y"), Hour = sapply(Time, get_hour)) %>%
group_by(Year, DayOfWeek, Hour) %>%
summarize(count = n()) %>%
group_by(Year) %>%
mutate(norm = count/sum(count))
df_arrest_time_year$DayOfWeek <- factor(df_arrest_time_year$DayOfWeek, level = rev(dow_format))
df_arrest_time_year$Hour <- factor(df_arrest_time_year$Hour, level = 0:23, label = hour_format)
df_arrest_time_year %>% head(10)
Out[21]:
In [22]:
plot <- ggplot(df_arrest_time_year, aes(x = Hour, y = DayOfWeek, fill = norm)) +
geom_tile() +
fte_theme() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.6, size = 4)) +
labs(x = "Hour of Arrest (Local Time)", y = "Day of Week of Arrest", title = "Police Arrests in San Francisco from 2003 – 2015 by Time of Arrest, Normalized by Year") +
scale_fill_gradient(low = "white", high = "#E67E22") +
facet_wrap(~ Year, nrow = 6)
max_save(plot, "sf-arrest-when-7", "SF OpenData", w = 6, h = 6, tall = T)
Ack, not really.
Let's try working with maps. (Ed. Note: Due to their size, the maps will not be embedded directly into the notebook, but they will be available in the repository.}
We can use the CSV output of the Bounding Box Tool to easily choose explicit bounds.
In [23]:
bbox = c(-122.516441,37.702072,-122.37276,37.811818)
# credit to /u/all_genes_considered for map setting suggestion
map <- get_map(location = bbox, source = "stamen", maptype = "toner-lite")
Test map download.
In [64]:
png("sf-arrest-where-0.png", w=900, h=900, res=300)
ggmap(map)
dev.off()
Out[64]:
The "white space" issue noted in the bootstrap article is still present due to the fixed ratio of the ggmap. You will need to tweak chart dimensions accordingly.
In [24]:
plot <- ggmap(map) +
geom_point(data = df_arrest, aes(x=X, y=Y), color = "#27AE60", size = 0.5, alpha = 0.01) +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
theme(plot.margin = unit(c(0.3, 0.3, -0.25, 0), "cm")) +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015")
max_save(plot, "sf-arrest-where-1", "SF OpenData", w = 3.8, h = 4)
We can facet the map by the Type of Crime using facet_wrap
. (contrary to notes in the documentation, setting the ggplot as the base_layer
is apparently not necessary, and imposes a performance penalty)
In [25]:
plot <- ggmap(map) +
geom_point(data = df_arrest %>% filter(Category %in% df_top_crimes$Category[2:19]), aes(x=X, y=Y, color=Category), size=0.75, alpha=0.05) +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, by Type of Crime") +
facet_wrap(~ Category, nrow = 3)
max_save(plot, "sf-arrest-where-2", "SF OpenData", w = 14.2, h = 8, tall = T)
Now let's normalize the above plot for each facter, with Hex aggregation.
In [38]:
# Do not show hex if sum is below threshold
sum_thresh <- function(x, threshold = 10^-3) {
if (sum(x) < threshold) {return (NA)}
else {return (sum(x))}
}
plot <- ggmap(map) +
stat_summary_hex(data = df_arrest %>% filter(Category %in% df_top_crimes$Category[2:19]) %>% group_by(Category) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#2980B9") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Type of Crime") +
facet_wrap(~ Category, nrow = 3)
max_save(plot, "sf-arrest-where-3", "SF OpenData", w = 14.2, h = 8, tall = T)
Facet by police districts.
In [56]:
plot <- ggmap(map) +
stat_summary_hex(data = df_arrest %>% group_by(PdDistrict) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#8E44AD") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Police District") +
facet_wrap(~ PdDistrict, nrow = 2)
max_save(plot, "sf-arrest-where-4", "SF OpenData", w = 13, h = 6, tall = T)
Facet by months. (The raw month must be appended to the original df_arrest
data frame now)
In [55]:
df_arrest <- df_arrest %>% mutate(Month=format(as.Date(Date, "%m/%d/%Y"), "%B"))
df_arrest$Month <- factor(df_arrest$Month,
level = c("January","February","March","April","May","June","July","August","September","October","November","December"))
plot <- ggmap(map) +
stat_summary_hex(data = df_arrest %>% group_by(Month) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#E74C3C") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Month") +
facet_wrap(~ Month, nrow=2)
max_save(plot, "sf-arrest-where-5", "SF OpenData", w=13, h=5, tall=T)
Facet by year.
In [54]:
df_arrest <- df_arrest %>% mutate(Year=format(as.Date(Date, "%m/%d/%Y"), "%Y"))
plot <- ggmap(map) +
stat_summary_hex(data=df_arrest %>% group_by(Year) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#E67E22") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Year") +
facet_wrap(~ Year, nrow=2)
max_save(plot, "sf-arrest-where-6", "SF OpenData", w=10.5, h=4)
Facet by hour of day.
In [53]:
df_arrest <- df_arrest %>% mutate(Hour = sapply(Time, get_hour))
df_arrest$Hour <- factor(df_arrest$Hour, level = 0:23, label = hour_format)
plot <- ggmap(map) +
stat_summary_hex(data=df_arrest %>% group_by(Hour) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#1ABC9C") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Hour") +
facet_wrap(~ Hour, nrow=4)
max_save(plot, "sf-arrest-where-7", "SF OpenData", w=10.5, h=8, tall=T)
Facet by Day of Week
In [40]:
df_arrest$DayOfWeek <- factor(df_arrest$DayOfWeek, level = dow_format)
plot <- ggmap(map) +
stat_summary_hex(data=df_arrest %>% group_by(DayOfWeek) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#16A085") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by Day of Week") +
facet_wrap(~ DayOfWeek, nrow=2)
max_save(plot, "sf-arrest-where-8", "SF OpenData", w=10.5, h=6, tall=T)
Followup analysis to /u/NowProveIt's comment on Reddit suggesting that SSI payments lead to higher activity on Wednesday. Here's a code fragment to create a data frame of Wednesdays and their month-wise ordinals.
In [31]:
start_date <- "2003-01-01"
end_date <- "2015-11-15"
# Create a vector of all days between start and end date
days <- seq(as.Date(start_date), as.Date(end_date), "days")
df_dates <- tbl_df(data.frame(Date = days)) %>%
mutate(weekday = format(Date, "%A"),
month = format(Date, "%B"),
year = format(Date, "%Y"))
df_dates %>% head(10)
Out[31]:
Use window function shennanigans to get the ordinal ranks.
In [32]:
# Text values to replace numeric ordinals
ordinals <- c("First", "Second", "Third", "Fourth")
df_dates <- df_dates %>%
filter(weekday == "Wednesday") %>%
group_by(year, month) %>%
mutate(rank = rank(Date)) %>%
filter(rank <= 4) %>% # removes the rare 5th Wednesday
mutate(Date = format(Date, format = "%m/%d/%Y"), # needs to be proper format for merging
rank = factor(rank, levels = 1:4, labels = ordinals),
ordinal = paste(rank, weekday))
df_dates %>% head(10)
Out[32]:
Combine with the arrest data frame.
In [49]:
df_arrest_wed <- df_arrest %>%
filter(DayOfWeek == "Wednesday") %>%
inner_join(df_dates) %>%
select(Date, Time, X, Y, ordinal)
sprintf("NA values present from Merge: %s", sum(is.na(df_arrest_wed %>% select(ordinal))) > 0)
set.seed(42)
df_arrest_wed %>% sample_n(10)
Out[49]:
Out[49]:
In [50]:
df_arrests_ord <- df_arrest_wed %>%
mutate(Hour = sapply(Time, get_hour)) %>%
group_by(ordinal, Hour) %>%
summarize(count = n())
df_arrests_ord %>% head(10)
Out[50]:
In [65]:
df_arrests_ord$ordinal <- factor(df_arrests_ord$ordinal, levels = c("First Wednesday", "Second Wednesday", "Third Wednesday", "Fourth Wednesday"))
plot <- ggplot(df_arrests_ord, aes(x = Hour, y = count, color = ordinal)) +
geom_line() +
fte_theme() +
scale_x_continuous(breaks = c(0,4,8,12,16,20), labels = c("12 AM", "4 AM", "8 AM", "12 PM", "4 PM", "8 PM")) +
scale_y_continuous(labels = comma) +
theme(legend.title = element_blank(), legend.position="top", legend.direction="horizontal", legend.key.height=unit(0.25, "cm"), legend.margin=unit(-0.5,"cm")) +
labs(x = "Hour of Arrest (Local Time)", y = "Total # of Arrests by Hour", title = "# of Police Arrests in San Francisco from 2003 – 2015 on Wednesdays, by Hour")
max_save(plot, "ssi-crime-1", "SF OpenData", w = 5)
Create a normallized map of the Wednesdays, because why not?
In [52]:
df_arrest_wed$ordinal <- factor(df_arrest_wed$ordinal, levels = c("First Wednesday", "Second Wednesday", "Third Wednesday", "Fourth Wednesday"))
plot <- ggmap(map) +
stat_summary_hex(data=df_arrest_wed %>% group_by(ordinal) %>% mutate(w=1/n()), aes(x=X, y=Y, z=w), fun=sum_thresh, alpha = 0.8, color="#CCCCCC") +
fte_theme() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank()) +
scale_fill_gradient(low = "#DDDDDD", high = "#E74C3C") +
labs(title = "Locations of Police Arrests Made in San Francisco from 2003 – 2015, Normalized by # Wednesday") +
facet_wrap(~ ordinal, nrow=2)
max_save(plot, "ssi-crime-2", "SF OpenData", w = 5.5, h = 6, tall=T)
Copyright (c) 2015 Max Woolf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.