Introduction

The data used in this study to visualise policing in Dallas, Texas. It demonstrates the correlation between various officer and subject parameters. It illustrates the connection between subject gender and race, as well as officer gender and race. the description of the subject and the type of force employed by various officers according to race. Additionally, it depicts the city’s policing incidents. The study displays temporal patterns, incident counts by subject race and officer race over months and days, central tendencies of incident rates across subject races, and distributions of incidents across months. Tables, bar plots, stacked bar plots, density plots, and an interactive map made in R using the Leaflet library are just a few of the ways the data is visualised. Overall, the study offers insightful information about police statistics in Dallas, Texas.

Method

We are provided with the policing data for Dallas, Texas, for 2016. The first thing I did was change the working directory and load the CSV file. I then install all the necessary packages I intend to use. I did some data cleaning and conversion of some variables to a desired format for visualisation. I analyse the relationship between police officers’ race, gender, and use of force incidents in a given population. I also use several tables and visualisations to illustrate these relationships. I create three different time series plots: one for the incident counts over the entire year, one for the incident counts by month, and one for the incident counts by hour of the day. I then create two density plots for the number of incidents by month and day: a box plot for the incident rates across races and a line plot for the incident rates by race. Finally, I created an interactive map using the Leaflet Library. Markers are added to the map with popups displaying incident information such as description, date, time, location, and longitude and latitude coordinates. The map also includes layer control to switch between different tile providers.

knitr::opts_chunk$set(warning = FALSE, message = FALSE, echo = TRUE)

Packages:

All the packages needed for thia project are installed and their libraries called

if(!is.null(dev.list())) dev.off()  # clear out the past 
## null device 
##           1
rm(list = ls())
cat("\014")
#load neccesary packages
library(ggmap)
library(shiny)
library(leaflet)
library(RColorBrewer)
library(tidyverse)
library(dplyr)
library(leaflet.extras)
library(lubridate)
library(gridExtra)
library(tidyr)
library(DT)
library(ggplot2)
library(ggridges)
library(viridis)
library(ggplot2)
library(plotly)
library(ggrepel)

Load Data:

I loaded the data “police.csv” and the structure and the head of the data frame. I showed the first 3 rows of the head.

 #Load the data and show the head and strcture of the Data
police_data <- read.csv("C:/MA304/Course work/police.csv") #load the data
str(police_data) # structure of the data
## 'data.frame':    2384 obs. of  47 variables:
##  $ INCIDENT_DATE                               : chr  "OCCURRED_D" "9/3/16" "3/22/16" "5/22/16" ...
##  $ INCIDENT_TIME                               : chr  "OCCURRED_T" "4:14:00 AM" "11:00:00 PM" "1:29:00 PM" ...
##  $ UOF_NUMBER                                  : chr  "UOFNum" "37702" "33413" "34567" ...
##  $ OFFICER_ID                                  : chr  "CURRENT_BA" "10810" "7706" "11014" ...
##  $ OFFICER_GENDER                              : chr  "OffSex" "Male" "Male" "Male" ...
##  $ OFFICER_RACE                                : chr  "OffRace" "Black" "White" "Black" ...
##  $ OFFICER_HIRE_DATE                           : chr  "HIRE_DT" "5/7/14" "1/8/99" "5/20/15" ...
##  $ OFFICER_YEARS_ON_FORCE                      : chr  "INCIDENT_DATE_LESS_" "2" "17" "1" ...
##  $ OFFICER_INJURY                              : chr  "OFF_INJURE" "No" "Yes" "No" ...
##  $ OFFICER_INJURY_TYPE                         : chr  "OFF_INJURE_DESC" "No injuries noted or visible" "Sprain/Strain" "No injuries noted or visible" ...
##  $ OFFICER_HOSPITALIZATION                     : chr  "OFF_HOSPIT" "No" "Yes" "No" ...
##  $ SUBJECT_ID                                  : chr  "CitNum" "46424" "44324" "45126" ...
##  $ SUBJECT_RACE                                : chr  "CitRace" "Black" "Hispanic" "Hispanic" ...
##  $ SUBJECT_GENDER                              : chr  "CitSex" "Female" "Male" "Male" ...
##  $ SUBJECT_INJURY                              : chr  "CIT_INJURE" "Yes" "No" "No" ...
##  $ SUBJECT_INJURY_TYPE                         : chr  "SUBJ_INJURE_DESC" "Non-Visible Injury/Pain" "No injuries noted or visible" "No injuries noted or visible" ...
##  $ SUBJECT_WAS_ARRESTED                        : chr  "CIT_ARREST" "Yes" "Yes" "Yes" ...
##  $ SUBJECT_DESCRIPTION                         : chr  "CIT_INFL_A" "Mentally unstable" "Mentally unstable" "Unknown" ...
##  $ SUBJECT_OFFENSE                             : chr  "CitChargeT" "APOWW" "APOWW" "APOWW" ...
##  $ REPORTING_AREA                              : chr  "RA" "2062" "1197" "4153" ...
##  $ BEAT                                        : chr  "BEAT" "134" "237" "432" ...
##  $ SECTOR                                      : chr  "SECTOR" "130" "230" "430" ...
##  $ DIVISION                                    : chr  "DIVISION" "CENTRAL" "NORTHEAST" "SOUTHWEST" ...
##  $ LOCATION_DISTRICT                           : chr  "DIST_NAME" "D14" "D9" "D6" ...
##  $ STREET_NUMBER                               : chr  "STREET_N" "211" "7647" "716" ...
##  $ STREET_NAME                                 : chr  "STREET" "Ervay" "Ferguson" "bimebella dr" ...
##  $ STREET_DIRECTION                            : chr  "street_g" "N" "NULL" "NULL" ...
##  $ STREET_TYPE                                 : chr  "street_t" "St." "Rd." "Ln." ...
##  $ LOCATION_FULL_STREET_ADDRESS_OR_INTERSECTION: chr  "Street Address" "211 N ERVAY ST" "7647 FERGUSON RD" "716 BIMEBELLA LN" ...
##  $ LOCATION_CITY                               : chr  "City" "Dallas" "Dallas" "Dallas" ...
##  $ LOCATION_STATE                              : chr  "State" "TX" "TX" "TX" ...
##  $ LOCATION_LATITUDE                           : chr  "Latitude" "32.782205" "32.798978" "32.73971" ...
##  $ LOCATION_LONGITUDE                          : chr  "Longitude" "-96.797461" "-96.717493" "-96.92519" ...
##  $ INCIDENT_REASON                             : chr  "SERVICE_TY" "Arrest" "Arrest" "Arrest" ...
##  $ REASON_FOR_FORCE                            : chr  "UOF_REASON" "Arrest" "Arrest" "Arrest" ...
##  $ TYPE_OF_FORCE_USED1                         : chr  "ForceType1" "Hand/Arm/Elbow Strike" "Joint Locks" "Take Down - Group" ...
##  $ TYPE_OF_FORCE_USED2                         : chr  "ForceType2" "" "" "" ...
##  $ TYPE_OF_FORCE_USED3                         : chr  "ForceType3" "" "" "" ...
##  $ TYPE_OF_FORCE_USED4                         : chr  "ForceType4" "" "" "" ...
##  $ TYPE_OF_FORCE_USED5                         : chr  "ForceType5" "" "" "" ...
##  $ TYPE_OF_FORCE_USED6                         : chr  "ForceType6" "" "" "" ...
##  $ TYPE_OF_FORCE_USED7                         : chr  "ForceType7" "" "" "" ...
##  $ TYPE_OF_FORCE_USED8                         : chr  "ForceType8" "" "" "" ...
##  $ TYPE_OF_FORCE_USED9                         : chr  "ForceType9" "" "" "" ...
##  $ TYPE_OF_FORCE_USED10                        : chr  "ForceType10" "" "" "" ...
##  $ NUMBER_EC_CYCLES                            : chr  "Cycles_Num" "NULL" "NULL" "NULL" ...
##  $ FORCE_EFFECTIVE                             : chr  "ForceEffec" " Yes" " Yes" " Yes" ...
head(police_data, n = 3) # liss the first 3 rows.
##   INCIDENT_DATE INCIDENT_TIME UOF_NUMBER OFFICER_ID OFFICER_GENDER OFFICER_RACE
## 1    OCCURRED_D    OCCURRED_T     UOFNum CURRENT_BA         OffSex      OffRace
## 2        9/3/16    4:14:00 AM      37702      10810           Male        Black
## 3       3/22/16   11:00:00 PM      33413       7706           Male        White
##   OFFICER_HIRE_DATE OFFICER_YEARS_ON_FORCE OFFICER_INJURY
## 1           HIRE_DT    INCIDENT_DATE_LESS_     OFF_INJURE
## 2            5/7/14                      2             No
## 3            1/8/99                     17            Yes
##            OFFICER_INJURY_TYPE OFFICER_HOSPITALIZATION SUBJECT_ID SUBJECT_RACE
## 1              OFF_INJURE_DESC              OFF_HOSPIT     CitNum      CitRace
## 2 No injuries noted or visible                      No      46424        Black
## 3                Sprain/Strain                     Yes      44324     Hispanic
##   SUBJECT_GENDER SUBJECT_INJURY          SUBJECT_INJURY_TYPE
## 1         CitSex     CIT_INJURE             SUBJ_INJURE_DESC
## 2         Female            Yes      Non-Visible Injury/Pain
## 3           Male             No No injuries noted or visible
##   SUBJECT_WAS_ARRESTED SUBJECT_DESCRIPTION SUBJECT_OFFENSE REPORTING_AREA BEAT
## 1           CIT_ARREST          CIT_INFL_A      CitChargeT             RA BEAT
## 2                  Yes   Mentally unstable           APOWW           2062  134
## 3                  Yes   Mentally unstable           APOWW           1197  237
##   SECTOR  DIVISION LOCATION_DISTRICT STREET_NUMBER STREET_NAME STREET_DIRECTION
## 1 SECTOR  DIVISION         DIST_NAME      STREET_N      STREET         street_g
## 2    130   CENTRAL               D14           211       Ervay                N
## 3    230 NORTHEAST                D9          7647    Ferguson             NULL
##   STREET_TYPE LOCATION_FULL_STREET_ADDRESS_OR_INTERSECTION LOCATION_CITY
## 1    street_t                               Street Address          City
## 2         St.                               211 N ERVAY ST        Dallas
## 3         Rd.                             7647 FERGUSON RD        Dallas
##   LOCATION_STATE LOCATION_LATITUDE LOCATION_LONGITUDE INCIDENT_REASON
## 1          State          Latitude          Longitude      SERVICE_TY
## 2             TX         32.782205         -96.797461          Arrest
## 3             TX         32.798978         -96.717493          Arrest
##   REASON_FOR_FORCE   TYPE_OF_FORCE_USED1 TYPE_OF_FORCE_USED2
## 1       UOF_REASON            ForceType1          ForceType2
## 2           Arrest Hand/Arm/Elbow Strike                    
## 3           Arrest           Joint Locks                    
##   TYPE_OF_FORCE_USED3 TYPE_OF_FORCE_USED4 TYPE_OF_FORCE_USED5
## 1          ForceType3          ForceType4          ForceType5
## 2                                                            
## 3                                                            
##   TYPE_OF_FORCE_USED6 TYPE_OF_FORCE_USED7 TYPE_OF_FORCE_USED8
## 1          ForceType6          ForceType7          ForceType8
## 2                                                            
## 3                                                            
##   TYPE_OF_FORCE_USED9 TYPE_OF_FORCE_USED10 NUMBER_EC_CYCLES FORCE_EFFECTIVE
## 1          ForceType9          ForceType10       Cycles_Num      ForceEffec
## 2                                                      NULL             Yes
## 3                                                      NULL             Yes

Remove first role:

The data frame have 2 different column name, i removed one to prevent calling wrong column name or having confusion

# the data has 2 heading, remove one of the heading
police_data <- police_data[-1,]

Conversion of Variable:

I converted most of the variables to a format needed for visualization. Some to numeric, some to Interger and some to numeric. I also converted the variables with time to the right format also.

#convert some columns to the right format.
police_data$INCIDENT_DATE <- parse_date_time(police_data$INCIDENT_DATE, orders = c("mdy", "dmy", "ymd"))
police_data$INCIDENT_TIME <- as.POSIXct(police_data$INCIDENT_TIME, format="%I:%M:%S %p")
police_data$INCIDENT_TIME <- format(police_data$INCIDENT_TIME, format = "%H:%M:%S")
police_data$OFFICER_HIRE_DATE <- parse_date_time(police_data$OFFICER_HIRE_DATE, orders = c("mdy", "dmy", "ymd"))
police_data$OFFICER_GENDER  <- as.factor(police_data$OFFICER_GENDER )
police_data$OFFICER_YEARS_ON_FORCE <- as.numeric(police_data$OFFICER_YEARS_ON_FORCE)
police_data$OFFICER_RACE <- as.factor(police_data$OFFICER_RACE)
police_data$OFFICER_INJURY <- as.factor(police_data$OFFICER_INJURY )
police_data$OFFICER_INJURY_TYPE <- as.factor(police_data$OFFICER_INJURY_TYPE)
police_data$OFFICER_HOSPITALIZATION <- as.factor(police_data$OFFICER_HOSPITALIZATION)
police_data$SUBJECT_RACE <- as.factor(police_data$SUBJECT_RACE)
police_data$SUBJECT_GENDER <- as.factor(police_data$SUBJECT_GENDER)
police_data$SUBJECT_INJURY <- as.factor(police_data$SUBJECT_INJURY)
police_data$SUBJECT_INJURY_TYPE <- as.factor(police_data$SUBJECT_INJURY_TYPE)
police_data$SUBJECT_WAS_ARRESTED <- as.factor(police_data$SUBJECT_WAS_ARRESTED)
police_data$SUBJECT_OFFENSE <- as.factor(police_data$SUBJECT_OFFENSE)
police_data$SUBJECT_DESCRIPTION <- as.factor(police_data$SUBJECT_DESCRIPTION)
police_data$SUBJECT_OFFENSE <- as.numeric(police_data$SUBJECT_OFFENSE)
police_data$REPORTING_AREA <- as.integer(police_data$REPORTING_AREA)
police_data$SECTOR <- as.factor(police_data$SECTOR)
police_data$LOCATION_DISTRICT <- as.factor(police_data$LOCATION_DISTRICT)
police_data$LOCATION_CITY <- as.factor(police_data$LOCATION_CITY)
police_data$LOCATION_LATITUDE<- as.numeric(police_data$LOCATION_LATITUDE)
police_data$LOCATION_LONGITUDE <- as.numeric(police_data$LOCATION_LONGITUDE)
police_data$REASON_FOR_FORCE <- as.factor(police_data$REASON_FOR_FORCE)
police_data$OFFICER_YEARS_ON_FORCE <- as.numeric(police_data$OFFICER_YEARS_ON_FORCE)

Tables.

Table 1:

This table display the officers race with their gender .The table shows that the majority of officers are male, with the highest number of officers being white males, followed by Hispanic males and black males. There are also a smaller number of female officers, with the highest number being white females, followed by Hispanic females and black female

#table 1: This table shows the relationship between officer race  and gender
officer_race_gender <- table(police_data$OFFICER_RACE, police_data$OFFICER_GENDER)
# Display the table
ftable(officer_race_gender)
##               Female Male
##                          
## American Ind       2    6
## Asian              7   48
## Black             49  292
## Hispanic          42  440
## Other              6   21
## White            134 1336
Table 2:

This table calculates row and column percentages for the officer race and gender. It shows the proportion of female and male officers in each race category and the proportion of each race category in the total number of officers. For example, 25% of American Indian officers are female, while 75% are male. The “OffSex” column represents officers whose gender was not specified. The “Total” row and column represent the total number of officers and the total proportion of each gender, respectively.

This table provides a quick overview of the distribution of officer race and gender in the dataset and can be used to investigate any disparities in the use of force incidents across different officer demographics.

# table2: this table shows the race and gender in percentage rate
# Add row and column percentages to the table
officer_race_gender_prop <- prop.table(officer_race_gender, margin = 1)
officer_race_gender_prop <- cbind(officer_race_gender_prop, Total = rowSums(officer_race_gender_prop))
officer_race_gender_prop <- rbind(officer_race_gender_prop, Total = colSums(officer_race_gender_prop))
officer_race_gender_prop <- round(officer_race_gender_prop * 100, 2)
# Display the table with row and column percentages
ftable(officer_race_gender_prop)
##               Female   Male  Total
##                                   
## American Ind   25.00  75.00 100.00
## Asian          12.73  87.27 100.00
## Black          14.37  85.63 100.00
## Hispanic        8.71  91.29 100.00
## Other          22.22  77.78 100.00
## White           9.12  90.88 100.00
## Total          92.15 507.85 600.00
Table 3:

This table shows the number of subjects stopped or arrested by the police, broken down by their race and gender. The columns represent the subject’s race (American Indian, Asian, Black, etc.), and the rows represent their gender (Male, Female, Unknown, or NULL). The numbers in each cell represent the count of subjects that belong to that specific combination of race and gender. From this it can be infer that more black male have been stopped or arrested by the police and the lest arrested male are the American Indian. Black females are also mostly stopped or arrested among thode that identify as female.

# table 3 : this shows the number of subject race and their gender
ftable(police_data$SUBJECT_GENDER, police_data$SUBJECT_RACE)
##          American Ind Asian Black Hispanic NULL Other White
##                                                            
## Female              0     0   274       69    4     0    93
## Male                1     5  1058      455   25    11   377
## NULL                0     0     0        0   10     0     0
## Unknown             0     0     1        0    0     0     0
Table 4:

This shows the frequency and percentage of different subject descriptions recorded in the dataset. The data was sorted in decreasing order of frequency, and only descriptions with a frequency greater than 1 were included. The table contains six descriptions, including mentally unstable, alcohol, unknown, unknown drugs, none detected, and alcohol and unknown drugs.

The table shows that the most frequent subject description was “mentally unstable,” accounting for 17.3% of all recorded subject descriptions, followed by “alcohol” at 16.0%. The third most frequent subject description was “unknown” at 15.3%, followed by “unknown drugs” at 13.4%. “None detected” accounted for 12.5% of the descriptions, while “alcohol and unknown drugs” accounted for 11.8%.

This table can help identify patterns in subject behavior and assist law enforcement agencies in understanding the different types of incidents they may encounter in the field. It can also help inform policies and procedures related to police interactions with individuals who exhibit certain behaviors or have specific characteristics.

# Table 4: This table shows the frequency and percentage of each subject description
# Sort the subject description in descending order and store it in police_data_reason
police_data_reason <- sort(table(police_data$SUBJECT_DESCRIPTION), decreasing = TRUE)
# Create a data frame with subject descriptions that occur more than once
police_data_reason <- data.frame(police_data_reason[police_data_reason > 1])
# Rename the column names to "SUBJECT_DESCRIPTION" and "Frequency"
colnames(police_data_reason) <- c("SUBJECT_DESCRIPTION", "Frequency")
# Calculate the percentage of each subject description and add it as a new column
police_data_reason$Percentage <- police_data_reason$Frequency / sum(police_data_reason$Frequency)
# Display the data table using the DataTables library with a horizontal scroll bar
datatable(police_data_reason, options = list(scrollX='400px'))

Visualization:

Plot 1

The resulting plot shows the frequency of each SUBJECT_DESCRIPTION on the y-axis and the SUBJECT_DESCRIPTION on the x-axis. The bars are colored according to the SUBJECT_DESCRIPTION. This plot can help us to easily see the most frequent SUBJECT_DESCRIPTION and compare the frequencies of different SUBJECT_DESCRIPTION. The top 5 most frequent SUBJECT_DESCRIPTION are “Mentally unstable”, “Alcohol”, “Unknown”, “Unknown Drugs” and “None detected”.

#Visualization
#1
#this is a bar plot that shows subject description
subject_description_offence <-ggplot(police_data_reason, aes(x=SUBJECT_DESCRIPTION, y=Frequency, #
      fill=SUBJECT_DESCRIPTION)) + geom_bar(stat="identity") + 
  theme(axis.text.x=element_blank()) + geom_text_repel(data=police_data_reason, aes(label=SUBJECT_DESCRIPTION))
subject_description_offence

##### Plot2:

The plot visualizes the relationship between the subject’s race and gender across different subject descriptions. The x-axis represents the subject race, and the fill color represents the subject gender. The position argument is set to “fill,” which stacks the bars to show the proportion of each gender within each race. This plot helps to explore any patterns or differences in the proportions of subject race and gender across different subject descriptions.

#2

#subject description with race and gender

ggplot(data = police_data, aes(x = SUBJECT_RACE, fill = SUBJECT_GENDER)) +
  geom_bar(position = "fill") +
  facet_wrap(~ SUBJECT_DESCRIPTION, ncol = 3) +
  labs(x = "Subject Race", y = "Proportion", fill = "Subject Gender")

Plot 3:

This stacked barplot that shows the relationship between an officer’s race and gender. The plot shows that White are the most dominant among the police especially the white males while American Indians are the least. The plot shows the disparity in the number of police in Dallas

#3
## Barplot showing officers gender and race

# group the data by officer race and gender and count the number of occurrences
officer_race_gender <- police_data %>% 
  group_by(OFFICER_RACE, OFFICER_GENDER) %>% 
  summarise(count=n())

# plot a stacked bar plot
ggplot(officer_race_gender, aes(x=OFFICER_RACE, y=count, fill=OFFICER_GENDER)) + 
  geom_col(position="dodge") +
  labs(title="Relationship between Officer's Race and Gender", x="Officer Race", y="Count", fill="Officer Gender") +
  theme(plot.title = element_text(hjust = 0.5), legend.position = "bottom")

Plot 4:

This plot shows the relationship between the officers race, year on Force and the incident involving force. From the plot, it can be infer that most lager percentage of officers leaves work below 10 years of years in service. Other unspecified race, Blacks and Asian are more likely to leave work before the first 10 years in Service while Majority Officers above 30 years in service are White.

library(plotly)

# Compute count of incidents involving force by race and years on force
force_count <- police_data %>%
  group_by(OFFICER_RACE, OFFICER_YEARS_ON_FORCE) %>%
  summarize(Count = n(), .groups = 'drop')


# Create a scatter plot using plotly
fig <- plot_ly(force_count, x = ~OFFICER_YEARS_ON_FORCE, y = ~Count, color = ~OFFICER_RACE, type = "scatter", mode = "markers") %>%
  layout(title = "Relationship Between Officer Race, Years on Force, and Incidents Involving Force",
         xaxis = list(title = "Years on Force"),
         yaxis = list(title = "Count of Incidents Involving Force"),
         legend = list(title = "Officer Race", bgcolor = "#F5F5F5", bordercolor = "#FFFFFF", borderwidth = 1))

# Display the plot
fig
Plot 5:

This plot visualize the relationship between Officer Gender, Use of Of force and Hospitalization. It shows that majority of White Male officers uses force in over 50% of the Incident while Hispanic officers rank the next. White Male officers are also the most hospitalize followed by the Black officers. Most Female Officers do not use force and they are also less likely to have injury that will lead to Hospitalization.

#5
#officers race, gender and hospitalization 


ggplot(police_data, aes(x = OFFICER_GENDER, y = ..count../sum(..count..), fill = OFFICER_RACE)) +
  geom_bar(position = "dodge") +
  facet_wrap(~OFFICER_HOSPITALIZATION, ncol = 3) +
  scale_y_continuous(labels = scales::percent_format()) +
  labs(x = "Officer Gender", y = "Percentage of Total Use of Force Incidents", fill = "Officer Race") +
  ggtitle("Relationship Between Officer Gender, Race, and hospitalization") +
  theme_minimal()

##### Plot 6 :

This plot shows the relationship between the officer race and the type of force they use. It Shows that white officers resolve to force most. It also shows that black subject are more likely to be use force on onlike other subject from other races. Black are more likely to be force to comply byshow of weapon.

#6
# officer race, subject race and force used
orace_srace_force_used<- ggplot(police_data, aes(x = OFFICER_RACE, y = SUBJECT_RACE, color= TYPE_OF_FORCE_USED1))+
  geom_point() +
  labs( x = "officer race", y = "subject race", title = "force used on subject and race ")
ggplotly(orace_srace_force_used)

Time Series

Variable Conversion

These set variables, Incident time, Incident date are all convrted to the right for the time series visualizaton.

#time series
police_data$INCIDENT_DATE <- as.Date(police_data$INCIDENT_DATE, format = "%m/%d/%Y")
police_data$INCIDENT_DATE <- gsub("00","20",police_data$INCIDENT_DATE)
police_data$INCIDENT_DATE <- as.Date(police_data$INCIDENT_DATE, format = "%Y-%m-%d")
police_data$INCIDENT_TIME <- format(strptime(police_data$INCIDENT_TIME, "%I:%M:%S %p"), "%H:%M:%S")
police_data$INCIDENT_MONTH <- months(as.Date(police_data$INCIDENT_DATE))
police_data$INC_MONTH <-format(police_data$INCIDENT_DATE,"%m")
police_data$INCIDENT_HOUR <- as.numeric(substr(police_data$INCIDENT_TIME, 0, 2))
police_data$INCIDENT_DAY <- wday(police_data$INCIDENT_DATE, label=TRUE)
police_data$INC_HOUR <- substr(police_data$INCIDENT_TIME, 0, 2)
police_data$INC_DATE <- substr(police_data$INCIDENT_DATE, 9, 10)
# Create group of datas:

police_data_year <- police_data %>%
  group_by(INCIDENT_DATE, INCIDENT_MONTH, INCIDENT_DAY) %>%
  summarize(count = n(), .groups = "drop")

police_data_month <- police_data %>%
  group_by(INC_MONTH) %>%
  summarize(count = n(), .groups = "drop")

police_data_day <- police_data %>%
  group_by(INCIDENT_DAY, INCIDENT_HOUR) %>%
  summarize(count = n(), .groups = "drop")

police_data$INC_HOUR <- substr(police_data$INCIDENT_TIME, 0, 2)

police_data_hour_n <- police_data %>%
  group_by(INC_HOUR) %>%
  summarize(avg = n(), .groups = "drop")
Plot 7 and 8

These 2 time series plot show the Incident report per month in 2016. It shows that the highest number of incidents reported were in March which is above 25o. The Month of Feburay also have 250 incidents Reported. Lowest number of incidents were reported in December which is below 100. From the trend it can be infer that more incident report are made in the early part of the year while it tends togo down towards the ending of the year.

c1 <- ggplot(data = police_data_year, aes(INCIDENT_DATE, count)) +   geom_line(linewidth=0.5, col="gray") +
  geom_smooth(method = "loess", color = "red", span = 1/5) + theme_bw() + labs(x="Months ", y= "INCIDENT COUNTS", title="1.a Year vs Incidents")
 c1

r1 <- ggplot(police_data_month, aes(x=INC_MONTH, y =count, group=1)) + geom_line()  + geom_line( size = 1,colour ="steelblue") + labs(x="MONTHS OF 2016", y= "INCIDENT COUNTS", title="1.b Months vs  Incident Rates")  + theme_bw()

r1

##### Plot 9

r2 <- ggplot(police_data_hour_n, aes(x = INC_HOUR, y = avg, group = "count")) + geom_line( size = 1, colour = "orange") + labs(x="HOURS IN A DAY", y= "INCIDENT COUNTS", title="1.c Hours vs  Incident Rates")+ theme_bw() +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5)) +
  
  labs(x = "Hour of the day", y = "count") + theme_bw()
r2

Plot 10
r3 <- ggplot(police_data_year, aes(count)) +
  geom_density(alpha = 0.5, colour = "black", fill ="blue")+ labs(x="Incident counts", y= "Density", title="1.d Distribuion of incident rates") + theme_bw()

r3

Plot 10

This plot shows the incident counts are normally distributed in the months of March,June,July,January,August and April. Two peaks have been oberserved in the months of December,February,May and October. Left skweness is observed in September

p1 <- ggplot(police_data_year, aes(count, INCIDENT_MONTH, fill = INCIDENT_MONTH)) + geom_density_ridges(bandwidth = 0.1,size = 1) +
  #  scale_fill_viridis(name = "T_max [°C]", option = "C") +
  scale_x_log10() +
  
  theme(legend.position = "none") +
  
  labs(x = "Number of Incidents", y = "Months")

p1

##### Plot 11

this shows the days, we could observe the incident rate is normally distributed on Sundays. Multi modality is observed on Wednesdays. Small nodes can also be observed during Wednesday , Thursday , Friday and Saturday. The average range of incidents for days and months is between 3 to 20.

p2 <- ggplot(police_data_year, aes(count, INCIDENT_DAY, fill = INCIDENT_DAY)) +
  
  geom_density_ridges(bandwidth = 0.1,size = 1) + scale_x_log10() +
  
  theme(legend.position = "none") +
  
  labs(x = "Number of Incidents", y = "Days")

p2

#3
police_data_dateh <- police_data %>% 
  filter(SUBJECT_RACE %in% c( "American Indian", "Black", "White", "Hispanic", "Asian")) %>%
  group_by(INCIDENT_DATE, INC_MONTH, SUBJECT_RACE) %>%
  summarize(avg = n(), .groups = "drop")
Plot 12

This showws the central tendecy of Incident rate Across race. It shows that blacks are more tedency than other tribe.

g3 <- ggplot(police_data_dateh , aes(x = (INC_MONTH), y= avg, fill = INC_MONTH)) +
  
  geom_boxplot() +
  labs(x= 'days',y = 'Incident Rate', 
       title = paste("Central Tendency of", ' Incident rate across SUBJECT RACE ')) +
  # theme_bw() +
  theme(legend.position="none") + facet_wrap(~SUBJECT_RACE)  + 
  coord_cartesian(ylim = c(1, 12))
g3

#4

police_data_srace <- police_data %>%
  group_by(INC_MONTH, INCIDENT_MONTH, SUBJECT_RACE) %>%
  summarize(count = n(), .groups = "drop")

police_data_orace <- police_data %>%
  group_by(INC_MONTH, INCIDENT_MONTH, OFFICER_RACE) %>%
  summarize(count = n(), .groups = "drop")
Plot 13

This plot ahows clearly that Black are more likely to be involve in an incident than any other race.

c1 <- ggplot() +
  geom_line(data=subset(police_data_srace, SUBJECT_RACE=="American Ind" ) ,aes(y=count,x= INC_MONTH,colour="brown",group=1),size=1 ) +
  geom_line(data=subset(police_data_srace, SUBJECT_RACE=="Black" ) ,aes(y=count,x= INC_MONTH,colour="green",group=1),size=1 ) +
  geom_line(data=subset(police_data_srace, SUBJECT_RACE=="Hispanic" ) ,aes(y=count,x= INC_MONTH,colour="red",group=1),size=1 ) +
  geom_line(data=subset(police_data_srace, SUBJECT_RACE=="Asian" ) ,aes(y=count,x= INC_MONTH,colour="purple",group=1),size=1 ) +
  geom_line(data=subset(police_data_srace, SUBJECT_RACE=="White" ) ,aes(y=count,x= INC_MONTH,colour="orange",group=1),size=1 ) +
  scale_color_discrete(name = "Y series", labels = c("AMERICAN IND", "BLACKS", "WHITES","HISPANICS", "ASIAN")) + labs(x="Months of 2016", y= "Counts", title=" Subject Race vs Incidents")  +
  scale_color_discrete(name = "Legend", labels = c("AMERICAN IND", "BLACKS", "WHITES","HISPANICS", "ASIAN"))  + theme(axis.text.x=element_text( vjust=0.5),legend.position="bottom") +guides(colour=guide_legend(nrow=2))
c1

##### Plot 14 This plot shows the rate of incident and the number of incident handled by officers by race. It shows that white officer is more likely to handle and incident while American Indian are the least.

c2 <- ggplot() +
  geom_line(data=subset(police_data_orace, OFFICER_RACE=="American Ind" ) ,aes(y=count,x= INC_MONTH,colour="brown",group=1),size=1 ) +
  geom_line(data=subset(police_data_orace, OFFICER_RACE=="Black" ) ,aes(y=count,x= INC_MONTH,colour="green",group=1),size=1 ) +
  geom_line(data=subset(police_data_orace, OFFICER_RACE=="Hispanic" ) ,aes(y=count,x= INC_MONTH,colour="red",group=1),size=1 ) +
  geom_line(data=subset(police_data_orace, OFFICER_RACE=="Asian" ) ,aes(y=count,x= INC_MONTH,colour="purple",group=1),size=1 ) +
  geom_line(data=subset(police_data_orace, OFFICER_RACE=="White" ) ,aes(y=count,x= INC_MONTH,colour="orange",group=1),size=1 ) +
  scale_color_discrete(name = "Y series", labels = c("AMERICAN IND", "BLACKS", "WHITES","HISPANICS", "ASIAN")) + labs(x="Months of 2016", title=" Officer Race vs Incident Handled Rates")  +
  scale_color_discrete(name = "Legend", labels = c("AMERICAN IND", "BLACKS", "WHITES","HISPANICS", "ASIAN"))  + theme(axis.text.x=element_text( vjust=0.5),legend.position="bottom")+guides(colour=guide_legend(nrow=2))
c2

Plot 15

This plot display crime incident locations on the map using leaflet

#5



police_data$popup <- paste("<b>Incident #: </b>", police_data$SECTOR  ,
                           "<br>", "<b>Description: </b>", police_data$SUBJECT_DESCRIPTION,
                           
                           "<br>", "<b>Date: </b>", police_data$INCIDENT_DATE,
                           "<br>", "<b>Time: </b>", police_data$INCIDENT_TIME ,
                           "<br>", "<b>PD district: </b>", police_data$LOCATION_DISTRICT,
                           
                           "<br>", "<b>Address: </b>", police_data$REPORTING_AREA,
                           "<br>", "<b>Longitude: </b>", police_data$LOCATION_LONGITUDE,
                           "<br>", "<b>Latitude: </b>", police_data$LOCATION_LATITUDE)

leaflet(police_data, width = "100%") %>% addTiles() %>%
  addTiles(group = "OSM (default)") %>%
  addProviderTiles(provider = "Esri.WorldStreetMap",group = "World StreetMap") %>%
  addProviderTiles(provider = "Esri.WorldImagery",group = "World Imagery") %>%
  # addProviderTiles(provider = "NASAGIBS.ViirsEarthAtNight2012",group = "Nighttime Imagery") %>%
  addMarkers(lng = ~LOCATION_LONGITUDE, lat = ~LOCATION_LATITUDE, popup = police_data$popup, clusterOptions = markerClusterOptions()) %>%
  addLayersControl(
    baseGroups = c("OSM (default)","World StreetMap", "World Imagery"),
    options = layersControlOptions(collapsed = FALSE)
  )
map
## function (.x, .f, ..., .progress = FALSE) 
## {
##     map_("list", .x, .f, ..., .progress = .progress)
## }
## <bytecode: 0x0000020ab3226c68>
## <environment: namespace:purrr>

Email: