Plotting spatial neighbors in ggmap

June 15, 2015

(This article was first published on Maxwell B. Joseph, and kindly contributed to R-bloggers)

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.


# 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
  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") +

To leave a comment for the author, please follow the link and comment on their blog: Maxwell B. Joseph. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)