-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ1_Crime_By_Area.R
40 lines (36 loc) · 1.23 KB
/
Q1_Crime_By_Area.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
install.packages("treemapify")
install.packages("ggfittext")
# Load necessary libraries
library(ggplot2)
library(dplyr)
library(treemapify)
# Read the dataset
csv_files <- list.files(path = "data/", pattern = "*.csv", full.names = TRUE)
crime_data <- do.call(rbind, lapply(csv_files, read.csv))
# Summarize crimes by area and sort in descending order
area_summary <- crime_data %>%
group_by(AREA.NAME) %>%
summarize(Crime_Count = n(), .groups = "drop") %>%
mutate(Percentage = Crime_Count / sum(Crime_Count) * 100) %>%
arrange(desc(Crime_Count))
# Create a treemap with sorted data and conditional text color
ggplot(area_summary, aes(
area = Crime_Count,
fill = Crime_Count,
label = paste0(AREA.NAME, "\n", Crime_Count, "\n", "(", round(Percentage, 1), "%)")
)) +
geom_treemap(color = "white") + # Set line color to white
geom_treemap_text(
aes(colour = "darkslateblue"),
fontface = "bold",
place = "centre",
grow = FALSE, # Disable font resizing
size = 8 # Set a consistent font size
) +
scale_colour_identity() + # Use text color as specified in the data
scale_fill_gradient(low = "aliceblue", high = "steelblue") +
labs(
title = "Crimes by Area",
fill = "Crime Count"
) +
theme_minimal()