简体   繁体   中英

Plotting nb object in ggplot?

I would like to plot the outline of UK, along with an nb object that I generated from a spatial points dataframe.

The problem is that the outline of UK takes really, really long to plot --it keeps crashing my Rstudio. This for example, either take really long to load or my Rstudio just stops responding.

library(raster)    
UK_gadm <- getData("GADM", country="GB", level=0)
    plot(UK_gadm)

So I resorted to using ggplot2 from this solution where I can get the outline of UK like in a fraction of a second with the following commands:

library(ggplot2)
UK <- map_data(map = "world", region = "UK") # changed map to "world"
    ggplot(data = UK, aes(x = long, y = lat, group = group)) + 
      geom_polygon() +
      coord_map()

The issue now is that I would like the nb object to be plotting against the backdrop of the outline of UK -- however, this seems only achievable in base R like for example :

plot(orotl.shp, xlim=c(-125, -115), ylim=c(42,47))
plot(orstationc.neighbors.dist, orstationc.loc, add=T, lwd=2, col="blue")

Is there any way I could plot nb objects in ggplot or is there a way for R to plot the outline of UK without crashing my computer with the base R plot function?

Managed to find a fast, simple solution after a whole night of effort. Hope this helps someone else with a similar issue.

Just to elaborate on the goal: plot a neighbours object (nb) against a shapefile. This is to visualise the linkages among certain coordinates. After some googling, I think this can only be done with base R's plot function. The problem however, was loading a country's shapefile (downloaded from official sources/gadm)-- its too big.

To solve this issue, get a more generalised, simple map of the country via the maps package, turn it into a shapefile and then plot it alongside the neighbours object.

Here's the code:

library(spdep)

# get your neighbour object from your spatial points df
rest_neighbours <- dnearneigh(rest_spdf,0,1)

library(maps)

# get boundary of UK
UK_map <- sf::st_as_sf(maps::map(database='world',regions='UK', plot = FALSE, fill = TRUE))

# write to shapefile
st_write(UK_map, 'shapefiles/UK.shp')

# henceforth, we can just call the shapefile 
UK <- readOGR('shapefiles/UK.shp')

# plot the boundary and the neighbours
plot(UK)
plot(rest_neighbours, rest_coords, add=T, lwd=2, col="blue")

I did not realise that official boundary files are often really detailed which also means that they are really huge and I'm glad that there's ready-made watered down versions of the maps available in the maps package of r. (Sorry if you already knew -- I'm still learning!)

Hope this helps anyone else!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM