Retain "region" elements for when using fortify on a spatiallinesdataframe

38 views
Skip to first unread message

Dave Moyer

unread,
Apr 8, 2016, 2:39:29 PM4/8/16
to ggplot2
I'm layering multiple plots using ggplot 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'm unsure how to retain data elements from the original spatiallinesdataframe after fortify in order to use them later to change the color or shape of the lines.

Just two layers of the plot (the state outline and roads):

download data (requires an email, but it is immediate): Roads and Coast (I used the py file).  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(.../"Alaska_Coast_1000000_py.shp", 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")
coast
.df$long <- ifelse(coast.df$long>0,coast.df$long*-1,coast.df$long) ##fix Aleutian Islands


roads
<- readOGR(".../Major_Roads_ln.shp", layer = "Major_Roads_ln")
proj4string
(roads) <- CRS("+init=epsg:3338")
roads
<- spTransform(roads, CRS("+proj=longlat +datum=NAD83"))
roads$id
<- c(1:32) ##create id that allows me join data from original file to fortified data frame - just a guess at methods
roads
.df <- fortify(roads, region = "id") ##this is where I would love to be able to specify which roads are which


##this plot doesn't try to color the lines or anything, 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" or
  scale_color_brewer
() +
  theme
(legend.position = "none",
        panel
.background = element_blank(),
        axis
.text.y = element_blank(), axis.ticks.y = element_blank(),
        axis
.text.x = element_blank(), axis.ticks.x = element_blank(),
        axis
.title.y = element_blank(), axis.title.x = element_blank())

print(a4)




Thanks in advance for your help.  
Reply all
Reply to author
Forward
0 new messages