Geographic Data Analysis with sf and ggplot2

Geospatial data analysis is crucial for visualizing and analyzing spatial relationships. We’ll use the sf package for handling spatial data.

Step 1: Install and Load sf

rCopy codeinstall.packages("sf")
install.packages("ggplot2")  # Make sure ggplot2 is installed
library(sf)
library(ggplot2)

Step 2: Load Geographic Data

For this example, you can use built-in datasets or download shapefiles. Here, we’ll use a simple example with the nc dataset from the sf package.

rCopy code# Load the North Carolina shapefile (included in the sf package)
nc <- st_read(system.file("shape/nc.shp", package = "sf"))

# Plot the geographic data
ggplot(data = nc) +
  geom_sf() +
  labs(title = "North Carolina Counties",
       x = "Longitude", y = "Latitude") +
  theme_minimal()

Step 3: Analyze and Visualize Attributes

rCopy code# Calculate the area of each county and add it as a new column
nc$area <- st_area(nc)

# Plot with area as fill
ggplot(data = nc) +
  geom_sf(aes(fill = area)) +
  labs(title = "Area of North Carolina Counties",
       fill = "Area (sq meters)") +
  theme_minimal()

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *