I have spatial data in R which is loaded as a SpatialPolygonsDataFrame
:
library(sp)
library(tmap)
d <- readRDS("data.rds")
qtm(d)
For the example, I used data for Germany from http://www.gadm.org/download.
Below, you see the map plotted by qtm(d)
. However, I would like to display my own data. I have locations with longitude and lattitude, and I would like to count the number of points inside the mapped polygons and show those counts as the color of the map below.
I have no clue where to start. Is there a simple approach that maps locations to the polygons?
I'm not very experienced with spatial data, however, maybe you can use this as a starter:
library(sp)
library(raster)
library(rgeos)
# load map
d <- getData("GADM", country = "Germany", level = 2)
# generate some random points
set.seed(1)
p <- data.frame(
lon = jitter(sample(8:13, 20, T)),
lat = jitter(sample(49:52, 20, T))
)
# match points with polygons
mat <- gContains(d, SpatialPoints(p, proj4string=CRS(sp::proj4string(d))), byid=TRUE)
hits <- colSums(mat)
cols <- rev(heat.colors(diff(range(hits))+1))
# plot
plot(d, col = cols[hits+1], border = "green")
with(p, points(lon, lat, col = "blue", pch = 19, cex = .5))
来源:https://stackoverflow.com/questions/33067051/how-to-add-a-column-with-location-based-data-to-a-spatialpolygonsdataframe-in-r