I'm layering multiple plots using ggplot2 to create a map of Alaska that combines school location and the major road network. I've learned that despite being labeled "major roads" there is wide variance in quality, which is actually encoded in the original shapefile data in a variable called MIN
. I would like to illustrate road quality by coloring the line segments, but I'm unsure how to retain data elements from the original SpatialLinesDataFrame
object after fortify()
in order to use them later to change the color or shape of the lines.
This is a simplified version of the map I would like to make with just two layers of the plot (the state outline and roads):
To replicate my exact circumstance you can download my data here. The road data has a variable called MIN
that seems to encode road quality, which I would love to join to the final fortified data frame:
library(ggplot2)
library(rgeos)
library(maptools)
library(rgdal)
coast <- readOGR(".", layer = "Alaska_Coast_1000000_py")
proj4string(coast) <- CRS("+init=epsg:3338")
coast <- spTransform(coast, CRS("+proj=longlat +datum=NAD83"))
coast.df <- fortify(coast, region = "TYPE")
# fix Aleutian Islands
coast.df$long <- ifelse(coast.df$long>0, coast.df$long*-1, coast.df$long)
roads <- readOGR(".", layer = "Major_Roads_ln")
proj4string(roads) <- CRS("+init=epsg:3338")
roads <- spTransform(roads, CRS("+proj=longlat +datum=NAD83"))
# where I would love to have a "region" option as with polygons:
roads.df <- fortify(roads)
# this plot doesn't try to color the lines,
# but is the basis for what I'm hoping to adjust
a4 <- ggplot() +
geom_polygon(data = coast.df,
aes(x = long, y = lat, group = group),
color = "gray", size = 0.25, fill = "white") +
geom_path(data = roads.df, aes(x=long, y=lat, group=group),
size = 1)
# could imagine adding color = "road_type"
print(a4)