stats_nerd
stats_nerd

Reputation: 233

R- How to obtain a US Map with state boundaries using ggplot and sf, without using ggmap?

Over the weekend, I have been trying and failing to create a map of the US with state boundaries that I can draw a scatter plot on. The easiest way to do this previously seems to have been to do it with ggmaps, but google seems to have changed their APIs so I would have to enable them manually by entering a billing credit card, so that's not an option. The best alternative I could get is by using the sf library and the following code that I found in a tutorial, and it gives me the following plot without the state boundaries:

world <- getMap(resolution = "low")
class(world)
world <- st_as_sf(world)
class(world)

locdata= subset(pkdata,longitude!="NA" &latitude!='NA')

ggplot(data = world)+
  geom_sf(fill="grey")+
  geom_jitter(data= locdata, aes(longitude,latitude,col= age), alpha=0.5)+
  coord_sf(xlim = c(min(locdata$longitude)+37, max(locdata$longitude)), 
           ylim = c(min(locdata$latitude)+6, max(locdata$latitude)-10))+
  xlab("Longitude")+ 
  ylab("Latitude")+
  ggtitle("Police killing locations 2015-16")

enter image description here

Does someone know how I could sf or any other package to get a plot of the US with state boundaries without using ggmaps?

I have also found another page that seems to suggest using the code:

us <- map_data("state")
gg <- ggplot()+
  geom_map(data=us, map=us,aes(long, lat, map_id=region))

But strangely, even after loading the state maps correctly, I get the following error when trying to run this: "Warning: Ignoring unknown aesthetics: x, y"

Upvotes: 1

Views: 5391

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78792

library(sf)
library(tidyverse)

usa <- st_as_sf(maps::map("state", fill=TRUE, plot =FALSE))

ggplot(usa) +
  geom_sf(color = "#2b2b2b", fill = "white", size=0.125) +
  coord_sf(crs = st_crs("+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"), datum = NA) +
  ggthemes::theme_map()

enter image description here

Upvotes: 7

Related Questions