2

I'm trying to use the maps and mapdata packages with ggplot, but I can't seem to extract the coordinates out of the data. Specifically, I'm trying to plot certain US states and Canadian provinces.

library(maps)
library(mapdata)
library(ggplot2)
library(ggthemes)
library(raster)
us <- getData("GADM", country = "USA", level = 1)
canada <- getData("GADM", country = "CAN", level = 1)
states <- c('connecticut', 'new york', 'new jersey', 'massachusetts')
provinces <- c('Ontario', 'Alberta', 'Quebec')

us.states <- us[us$NAME_1 %in% states, ]
ca.provinces <- canada[canada$NAME_1 %in% provinces, ]

ggplot(us.states, aes(x = longitude, y = latitude, group = group)) +
  geom_path()+
  geom_path(data = ca.provinces)+
  coord_map()

and I get an error:

Regions defined for each Polygons
Regions defined for each Polygons
Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : 
  invalid graphics state

Any help here? I'm new to mapping in R.

Niklas Braun
  • 393
  • 3
  • 16

1 Answers1

2

The code was almost good. I just did some minor changes. 1. The state name and province names need to match exactly in the spatial polygon data frame. So the first letter of state names needs to be in upper case. and "Quebec" needs to be "Québec". 2. Change longitude and latitude to long and lat, respectively.

us <- getData("GADM", country = "USA", level = 1)
canada <- getData("GADM", country = "CAN", level = 1)
states <- c('Connecticut', 'New York', 'New Jersey', 'Massachusetts')
provinces <- c('Ontario', 'Alberta', 'Québec')

us.states <- us[us$NAME_1 %in% states, ]
ca.provinces <- canada[canada$NAME_1 %in% provinces, ]

ggplot(us.states, aes(x = long, y = lat, group = group)) +
  geom_path()+
  geom_path(data = ca.provinces)+
  coord_map()
www
  • 38,575
  • 12
  • 48
  • 84
  • Huh, I copy-pasted your code, and I get the same error: Regions defined for each Polygons Regions defined for each Polygons Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state Maybe dependencies? – Niklas Braun Apr 14 '17 at 19:20
  • 1
    Ahh. I fixed the error. See this thread: http://stackoverflow.com/questions/20155581/persistent-invalid-graphics-state-error-when-using-ggplot2 – Niklas Braun Apr 14 '17 at 19:28