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:


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" 



1 Answer 1


Merge the attribute table back to the fortified geometry:

# by.y=0 join by row.names
roads.df <- merge(fortify(roads), as.data.frame(roads), by.x="id", by.y=0)
p <- ggplot() +
               aes(x=long, y=lat, group=group, colour=MIN), size=1)


  • Very slick, thanks. I hadn't thought of the as.data.frame() piece and kept trying to work with the SpatialLinesDataFrame as it was.
    – Dave
    Apr 29, 2016 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.