Home > OS >  Adding coordinates as points to a map in R
Adding coordinates as points to a map in R

Time:07-19

I have a dataframe of sightings and objects with their latitudes and longitudes:

object = c("yacht", "fishingboat", "whale")
long = c(-123.02676, -123.39763, -123.25103)
lat = c(38.22033, 38.05059, 38.32280)
df = cbind.data.frame(long, lat)

I want to plot these points on a map of the world. I have created a map of the earth using the "rnaturalearth" package.

library(rnaturalearth)
library(sf)

world <- rnaturalearth::ne_countries(scale = "small", returnclass = "sf")

world %>% st_transform(crs = " proj=moll") %>%
  ggplot()   geom_sf()   theme_minimal()

As I said before, I want to plot the coordinates on the world map.

CodePudding user response:

You need to reproject these points, then you can use standard geom_point and geom_text. Your points are far too close together to see them all separately on a world map though:

df <-  sf::sf_project(" proj=longlat  datum=WGS84  ellps=WGS84  towgs84=0,0,0", 
                      " proj=moll", df) %>%
       as.data.frame() %>%
      setNames(c("long", "lat")) %>%
      cbind(object = object)

world %>% 
  st_transform(crs = " proj=moll") %>%
  ggplot()   
  geom_sf()   
  theme_minimal()  
  geom_point(data = df, aes(long, lat))  
  geom_text(data = df, aes(long, lat, label = object),
            vjust = c(1, 0, -1), hjust = 1)

enter image description here

If you zoom it, it is much clearer:

world %>% 
  st_transform(crs = " proj=moll") %>%
  ggplot()   
  geom_sf()   
  theme_minimal()  
  geom_point(data = df, aes(long, lat))  
  geom_text(data = df, aes(long, lat, label = object),
            vjust = c(0.5, 1, -1), hjust = 1.2)  
  coord_sf(ylim = c(4200000, 4700000), xlim = c(-10.75, -10.25) * 10^6)

enter image description here

  • Related