jc2525
jc2525

Reputation: 141

geom_map - names(map) not TRUE

I keep getting this error when trying to make a map...

Error in geom_map(data = all_states, map = all_states, mapping = aes(map_id = State, : all(c("x", "y", "id") %in% names(map)) is not TRUE

My code so far...

all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true",
                      header = TRUE,
                      sep = ";")

all_states$State = state.name[match(all_states$State, state.abb)]
all_states = na.omit(all_states)

ggplot(data = all_states, aes(map_id = State)) + 
  geom_map(data = all_states,
           map = all_states,
           mapping = aes(map_id=State,x=Longitude,y=Latitude)) +
  coord_fixed()

What am I doing wrong?

Upvotes: 0

Views: 574

Answers (1)

tjebo
tjebo

Reputation: 23737

2 Problems.

  • You did not download the correct map. geom_map needs data for creating polygons, but your data contains the coordinates for cities
  • geom_map is very peculiar and restrictive about column names in data frames

Solution

  • get the right map (e.g., Just use the maps package for US)
  • rename the columns

I have also removed one or two lines and 'fortified' the data frame, as this is usually recommended before using it for maps.

library(tidyverse)
all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true", header = TRUE, sep = ";")

all_states = na.omit(all_states) %>% 
  mutate(region = State, long=Longitude, lat = Latitude) %>%fortify

US <- map_data('usa')
#> 
#> Attaching package: 'maps'

#>     map
ggplot()+
  geom_map(data = US, map = US, mapping = aes( map_id = region, x = long, y = lat), fill = 'white') +
    # now this is the US background
  geom_point(data = filter(all_states, ! region %in% c('HI','AK','AS')), aes(x = long, y = lat), size = .01, color = 'black')
    # and this is YOUR data. Use geom_point for it!!! 
    #I have removed Alaska, Hawaii and a third little bit which I ignorantly don't know. 'AS'. 

#> Warning: Ignoring unknown aesthetics: x, y

Created on 2019-08-02 by the reprex package (v0.2.1)

Upvotes: 2

Related Questions