library(sf)
## Linking to GEOS 3.13.1, GDAL 3.11.4, PROJ 9.7.0; sf_use_s2() is TRUE
library(ggplot2)
library(leaflet)
# 1. Load the data (make sure the file is in your working directory)
df <- read.csv("C:/Users/Hp/Downloads/Coffee_Shops.csv")
# 2. Convert the data frame into a spatial object (sf)
# We specify the coordinates and the CRS (Coordinate Reference System)
# 4326 is the standard WGS84 system used by GPS
df_sf <- st_as_sf(df, coords = c("Longitude", "Latitude"), crs = 4326)
ggplot(data = df_sf) +
geom_sf(aes(size = Daily_Sales, color = Daily_Sales)) +
theme_minimal() +
labs(title = "Coffee Shop Sales Distribution",
subtitle = "Point Analysis in NYC")

leaflet(df) %>%
addTiles() %>% # Adds the default OpenStreetMap background
addMarkers(lng = ~Longitude,
lat = ~Latitude,
popup = ~paste(Store_Name, "<br>Sales: $", Daily_Sales))
# Load necessary libraries
library(sf)
library(ggplot2)
library(leaflet)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# 1. Create 200 observations of synthetic NYC data
set.seed(123) # Makes the "random" data the same every time you run it
n_points <- 200
nyc_data <- data.frame(
Store_ID = 1:n_points,
Store_Type = sample(c("Cafe", "Bakery", "Bookstore", "Gym"), n_points, replace = TRUE),
Daily_Sales = round(runif(n_points, 500, 3000), 0),
# Random coordinates within NYC bounds (approx Lat: 40.5-40.9, Long: -74.0 to -73.7)
Latitude = runif(n_points, 40.57, 40.88),
Longitude = runif(n_points, -74.05, -73.75)
)
# 2. Save this as an Excel-style CSV on your computer so you have it
write.csv(nyc_data, "nyc_business_data.csv", row.names = FALSE)
print(paste("Generated", nrow(nyc_data), "observations."))
## [1] "Generated 200 observations."
# Convert the data frame into a spatial 'sf' object
# 4326 is the CRS code for GPS coordinates (WGS84)
nyc_sf <- st_as_sf(nyc_data, coords = c("Longitude", "Latitude"), crs = 4326)
leaflet(nyc_data) %>%
addTiles() %>% # Base Map
addMarkers(
lng = ~Longitude,
lat = ~Latitude,
clusterOptions = markerClusterOptions(),
popup = ~paste0("<b>Type:</b> ", Store_Type, "<br><b>Sales:</b> $", Daily_Sales)
)
ggplot(nyc_data, aes(x = Longitude, y = Latitude)) +
stat_density_2d(aes(fill = ..level..), geom = "polygon", alpha = 0.4) +
scale_fill_gradient(low = "yellow", high = "red") +
geom_point(aes(color = Store_Type), size = 1) +
theme_minimal() +
labs(title = "Business Density Across NYC",
subtitle = "Heatmap showing concentration of store locations")
## Warning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(level)` instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

library(sf)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ lubridate 1.9.5 ✔ tibble 3.3.1
## ✔ purrr 1.2.1 ✔ tidyr 1.3.2
## ✔ readr 2.1.6
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ozmaps)
library(tmap)
# 1. Load Australian LGA boundaries from the ozmaps package
# We filter for a specific state (e.g., New South Wales or Queensland) to keep it focused
aus_map <- ozmap_data("abs_lga")
# 2. Create "Real-World" Synthetic Data
# Let's simulate 'Unemployment Rate' and 'Population Density' for 100+ LGAs
set.seed(42)
my_data <- data.frame(
NAME = aus_map$NAME,
Unemployment_Rate = runif(nrow(aus_map), 2, 12),
Pop_Density = runif(nrow(aus_map), 10, 500)
)
# 3. Join the spatial map with our data
map_combined <- aus_map %>%
left_join(my_data, by = "NAME") %>%
st_transform(3112) # Transform to GDA94 / Australian Albers (for accurate distance math)
library(spdep)
## Loading required package: spData
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
# 1. Define 'neighbors' (which LGAs touch each other?)
nb <- poly2nb(map_combined, queen = TRUE)
## Warning in poly2nb(map_combined, queen = TRUE): some observations have no neighbours;
## if this seems unexpected, try increasing the snap argument.
## Warning in poly2nb(map_combined, queen = TRUE): neighbour object has 9 sub-graphs;
## if this sub-graph count seems unexpected, try increasing the snap argument.
lw <- nb2listw(nb, style = "W", zero.policy = TRUE)
# 2. Calculate Local Gi* (Hotspot Analysis)
# This identifies areas where high values are surrounded by high values
map_combined$hotspot <- localG(map_combined$Unemployment_Rate, lw)
# 3. Convert to a readable scale
map_combined <- map_combined %>%
mutate(hotspot_category = case_when(
hotspot > 2.58 ~ "99% Hotspot",
hotspot > 1.96 ~ "95% Hotspot",
hotspot < -2.58 ~ "99% Coldspot",
hotspot < -1.96 ~ "95% Coldspot",
TRUE ~ "Not Significant"
))
# Set tmap to interactive mode
tmap_mode("view")
## ℹ tmap modes "plot" - "view"
## ℹ toggle with `tmap::ttm()`
tm_shape(map_combined) +
tm_polygons("hotspot_category",
palette = "-RdBu",
title = "Unemployment Hotspots",
popup.vars = c("NAME", "Unemployment_Rate")) +
tm_layout(title = "Australia Spatial Analysis")
##
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_tm_polygons()`: migrate the argument(s) related to the scale of
## the visual variable `fill` namely 'palette' (rename to 'values') to fill.scale
## = tm_scale(<HERE>).[v3->v4] `tm_polygons()`: migrate the argument(s) related to the legend of the
## visual variable `fill` namely 'title' to 'fill.legend = tm_legend(<HERE>)'[v3->v4] `tm_layout()`: use `tm_title()` instead of `tm_layout(title = )`Multiple palettes called "rd_bu" found: "brewer.rd_bu", "matplotlib.rd_bu". The first one, "brewer.rd_bu", is returned.
## [cols4all] color palettes: use palettes from the R package cols4all. Run
## `cols4all::c4a_gui()` to explore them. The old palette name "-RdBu" is named
## "rd_bu" (in long format "brewer.rd_bu")
# Quick example of the logic (Requires 'rayshader' package)
library(rayshader)
# 1. Create the ggplot
p <- ggplot(map_combined) +
geom_sf(aes(fill = Unemployment_Rate)) +
scale_fill_viridis_c()
# 2. Render in 3D
plot_gg(p, multicore = TRUE, width = 5, height = 5, scale = 250)