Search code examples
rgeospatialgeopandas

sf Point location off when plotting


I have a series of latitude and longitude points from Mexico in a csv that I am converting to an sf object. I was able to identify the crs using http://projfinder.com/.

library(sf)
library(spData)
library(tibble)

# basemap
mx = world %>% filter(iso_a2 == 'MX')
# cast to WGS84
mx = st_transform(mx, crs='EPSG:4326')

# mypoints
mypoints = tibble(
  latitude = c(19.46762, 32.63224, 18.94691, 19.28556, 18.92243),
  longitude = c(-98.14863, -115.5587, -103.9721, -99.13365, -99.22217)
)
mypoints_geo = st_as_sf(mypoints, coords = c("longitude", "latitude"), crs = 'EPSG:4326')


# plot
plot(mx['iso_a2'], axes=T)
plot(mypoints_geo, pch = 3, col = 'red', add=T)

As you can see in the first image, the points are not located in Mexico; in fact they don't even seem to be located where the lat/long values are. I attach another image from an alternative implementation I did in geopandas which works fine. How do I need to modify the R implementation to get the desired result?

enter image description here enter image description here

I have tried:

  • Changing the initial CRS and transforming to WGS84
  • geopandas implementation
  • Checked point locations with online tools
  • Alternatively implemented plotting with ggplot2.

The expected result is that from the geopandas implementation image above.


Solution

  • I managed to reproduce this on ggplot, here's the code I used:

    # Convert mx to WGS84
    mx <- st_transform(world %>% filter(iso_a2 == 'MX'), 
                       crs = 'EPSG:4326')
    
    # mypoints
    mypoints = tibble(
      latitude = c(19.46762, 32.63224, 18.94691, 19.28556, 18.92243),
      longitude = c(-98.14863, -115.5587, -103.9721, -99.13365, -99.22217)
    )
    
    mypoints_geo = st_as_sf(mypoints, coords = c("longitude", "latitude"), crs = 'EPSG:4326')
    
    # Plot using ggplot2
    ggplot() +
      geom_sf(data = mx, fill = "cornflowerblue", color = "black") +
      geom_sf(data = mypoints_geo, color = "red",fill = "red", size = 4, shape = 21) +
      theme_minimal()
    

    Output:

    enter image description here