# Plotting spatial neighbors in ggmap

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**Maxwell B. Joseph**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The R package spdep has great utilities to define spatial neighbors (e.g. `dnearneigh`

, `knearneigh`

, with a nice vignette to boot), but the plotting functionality is aimed at base graphics.
If you’re hoping to plot spatial neighborhoods as line segments in ggplot2, or ggmap, you’ll need the neighborhood data to be stored in a data frame.
So, to save others some trouble, I thought I’d share a little function that converts a spatial neighbors object (of class `nb`

) to a data frame.
This function is largely an alteration of the existing plotting function for base graphics, plot.nb.

library(spdep) data(nc.sids) # function converts nb object to a data.frame nb_to_df <- function(nb, coords){ x <- coords[, 1] y <- coords[, 2] n <- length(nb) cardnb <- card(nb) i <- rep(1:n, cardnb) j <- unlist(nb) return(data.frame(x=x[i], xend=x[j], y=y[i], yend=y[j])) } # create distance-based neighbors sids_nb <- dnearneigh(sidscents, d1=0, d2=80, longlat=T) nb_df <- nb_to_df(sids_nb, sidscents) # create data frame of coordinates coord_df <- data.frame(sidscents) names(coord_df) <- c("lon", "lat") # plot results with ggmap library(ggmap) basemap <- get_map("North Carolina", zoom=6) ggmap(basemap) + geom_segment(aes(x=x, xend=xend, y=y, yend=yend), data=nb_df) + geom_point(aes(x=lon, y=lat), data=coord_df) + ylab("Latitude") + xlab("Longitude")

To

**leave a comment**for the author, please follow the link and comment on their blog:**Maxwell B. Joseph**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.