goma
goma

Reputation: 21

ggplot error in unit(x, default.units) : 'x' and 'units' must have length > 0

I looked up "Data Visualization with ggplot2_Cheat Sheet_Rstudio _Maps" and tried to make Japanese version (but it didn't work as above). Please help me understand why the error "Error in unit(x,...." appears in this case.

library(ggplot2)
library(mapdata)

all = map_data("japan")
unique(all[, 5])
pref = c( #47 Japanese prefectures
  "Hokkaido",  "Aomori",    "Iwate",     "Miyagi",    "Akita",     "Yamagata",  "Fukushima",
  "Ibaraki",   "Tochigi",   "Gunma",     "Saitama",   "Chiba",     "Tokyo",     "Kanagawa", 
  "Niigata",   "Toyama",    "Ishikawa",  "Fukui",     "Yamanashi", "Nagano",    "Gifu",     
  "Shizuoka",  "Aichi",     "Mie",       "Shiga",     "Kyoto",     "Osaka",     "Hyogo",    
  "NARA",      "Wakayama",  "Tottori",   "Shimane",   "Okayama",   "Hiroshima", "Yamaguchi",
  "Tokushima", "Kagawa",    "Ehime",     "Kochi",     "Fukuoka",   "Saga",      "Nagasaki", 
  "Kumamoto",  "Oita",      "Miyazaki",  "Kagoshima", "Okinawa")

number = sample(1:20, 47, replace=TRUE) #random number
all_pref = as.data.frame(matrix(c(pref, number), 47, 2))

JP = ggplot2::map_data("japan")

DATA = data.frame(sample = as.numeric(all_pref$V2), 
                  japan = tolower(as.character(all_pref$V1)))

MAP = JP
k = ggplot(DATA, aes(fill = sample))

k + 
  geom_map(aes(map_id = japan), map=MAP) + 
  expand_limits(x = MAP$long, y = MAP$lat)

Error in unit(x, default.units): 'x' and 'units' must have length > 0

Upvotes: 2

Views: 5897

Answers (1)

krads
krads

Reputation: 1369

The place names you are matching between MAP and DATA are different mixed case versus lowercase.

I.e. MAP$region has mixed uppercase and lowercase letters e.g. 'Hokkaido' whereas DATA$japan has all lowercase names e.g. 'hokkaido'.

To allow ggplot to match across both, transform MAP as follows to convert the mixed case region names to all lowercase: MAP$region <- tolower(MAP$region)

Upvotes: 4

Related Questions