Add basemap to SpatialPointDataFrames using R

爱⌒轻易说出口 提交于 2019-12-10 21:10:14

问题


I want to add a basemap to my plot, which visualizes three SpatialPointDataFrames. I've already tried the maptools as well as RgoogleMaps package, but both don't work in the way, which I want to.
My problem: The SpatialPointDataFrames are not drawn on the GoogleMaps Background map.

A minimal example:

The city.csv with the following example content:

FID,city,POINT_X,POINT_Y
0,New York,-73.996786,40.720813
1,Newark,-74.172237, 40.732196

The R Code:

# Load packages
library(RgoogleMaps)
library(sp)

# load .csv file 
city= read.csv("city.csv", header = TRUE)

# convert to SpatialPointDataFrame
coordinates(city) <- c("POINT_X", "POINT_Y")
proj4string(city) <- CRS("+proj=longlat +datum=WGS84")

# use RgoogleMaps
gc <- geocode('new york, usa')
center <- as.numeric(gc)
ggmap(get_googlemap(center = center, color = 'bw', scale = 4), fullpage = T)
# Plot the city dataset
plot(city, pch = 22, col="black", bg= "yellow", cex = 1.5, add = TRUE)

The result should be a plot with the background map and the two points, but the points are not drawn on the map. Is there a geocoding problem or do I miss anything? Is it possible to combine ggmap and plt functions?

Any help is much appreciated!


回答1:


Using ggplot2 for this kind of work is much easier, you can add points, polygons, 2densities, etc... to ggmap layers.

library(RgoogleMaps)
library(sp)
library(ggplot2)
library(ggmap)

P is the SpatialPointsDataFrame object:

DB <- data.frame(FID=P$FID, city=P$city)
DB <- cbind(DB, P@coords)


DB <- data.frame(FID=c(0,1), city=c("New York", "Newark"),   POINT_X=c(-73.996786,-74.172237), POINT_Y=c(40.720813,40.732196 ))
gc <- geocode("new york, usa")
center <- as.numeric(gc)
G <- ggmap(get_googlemap(center = center, color = 'bw', scale = 4), extent = "device")
G1 <- G + geom_point(aes(x=POINT_X, y=POINT_Y ),data=DB, color="red", size=5)
plot(G1)

This is the output:




回答2:


These are two different frameworks (grid and base-graphics). Though, a combination of both may be possible, I would recommend to stick with ggplot.

You can easily add the points using geom_point(), see the answers here for example.




回答3:


More recently, other than ggplot2, there are also packages like leaflet and mapview that can handle this. In the case of Leaflet for R, see:

  • https://rstudio.github.io/leaflet/map_widget.html
  • https://rstudio.github.io/leaflet/basemaps.html


来源:https://stackoverflow.com/questions/22107216/add-basemap-to-spatialpointdataframes-using-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!