I am trying to overlay a map of country with pointers on specific locations. For this I first downloaded the boundary of country and then the lat/lon values of the points I want to plot
library(rgeoboundaries)
boundary <- geoboundaries("Mongolia")
library(MODIStools)
points <- mt_sites() %>%
filter(country == "Mongolia")
Then I tried to plot them together using ggplot2
but they dont overlay on each other.
library(ggplot2)
ggplot() +
geom_sf(data = boundary) +
geom_point(data = points,
aes(x = latitude,
y = longitude))
Your points
is a data.frame
not a SpatialPointsDataFrame
. So, first I have converted the data.frame
to SpatialPointsDataFrame
using coordinates(points) <- ~longitude + latitude
. Then I have assigned it a crs
(+proj=longlat +datum=WGS84 +no_defs
). Then I have converted the sp
object to sf
object using st_as_sf
and then I have plotted it like
library(rgeoboundaries)
library(raster)
library(tidyverse)
library(sf)
library(MODISTools)
boundary <- geoboundaries("Mongolia")
points <- mt_sites() %>%
filter(country == "Mongolia")
#Check the coordinate reference of points and boundary
crs(points)
#> [1] NA
crs(boundary)
#> CRS arguments: +proj=longlat +datum=WGS84 +no_defs
#See the class of the points
class(points)
#> [1] "data.frame"
#Convert the data.frame to SpatialPointsDataFrame
coordinates(points) <- ~longitude + latitude
#Assign the crs to points SpatialPointsDataFrame
crs(points) <- crs(boundary)
#Convert sp object to sf object
points_sf <- st_as_sf(points)
#Plot the results
ggplot() +
geom_sf(data = boundary) +
geom_sf(data = points_sf)