Search code examples
rmapsr-sf

Why is there a small part of the distribution map on the right side and how do I fix it using sf package in R?


I am trying to create a distribution map on North America. But a small part of the map is on the right side of the plot. The result is like in the screenshot.

Screenshot of the map:
Screenshot of the map

I tried it with sf package to put them together but somehow I could not.


Solution

  • On addition to @jindra-lacko's answer, you can use a specific projection suitable for contiguous US and Alaska. So no need to crop your object:

    library(sf)
    #> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
    library(dplyr)
    #> 
    #> Attaching package: 'dplyr'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    library(tigris)
    #> To enable caching of data, set `options(tigris_use_cache = TRUE)`
    #> in your R script or .Rprofile.
    library(ggplot2)
    
    # the one & only USA 
    states <- states() %>% 
      filter(!STUSPS %in% c('MP', 'VI', 'PR', 'GU', 'AS')) 
    
    ggplot(data = states) +
      geom_sf()
    

    enter image description here

    
    # Change CRS
    
    states_epsg <- st_transform(states, "ESRI:102008")
    
    
    ggplot(data = states_epsg) +
      geom_sf()
    

    enter image description here

    Created on 2023-05-19 with reprex v2.0.2