在Leaflet地图上注释数字变量

时间:2015-06-28 06:42:03

标签: r ggplot2 leaflet spatial

我做了这个情节

enter image description here

使用以下代码。

library(XML)
library(ggplot2)
library(scales)
library(plyr)
library(maps)

unemp <-
  readHTMLTable('http://www.bls.gov/web/laus/laumstrk.htm',
                colClasses = c('character', 'character', 'numeric'))[[2]]

names(unemp) <- c('rank', 'region', 'rate')
unemp$region <- tolower(unemp$region)

us_state_map <- map_data('state')
map_data <- merge(unemp, us_state_map, by = 'region')

map_data <- arrange(map_data, order)

states <- data.frame(state.center, state.abb)

p1 <- ggplot(data = map_data, aes(x = long, y = lat, group = group))
p1 <- p1 + geom_polygon(aes(fill = cut_number(rate, 5)))
p1 <- p1 + geom_path(colour = 'gray', linestyle = 2)
p1 <- p1 + scale_fill_brewer('Unemployment Rate (Jan 2011)', palette  = 'Set1')
p1 <- p1 + coord_map()
p1 <- p1 + geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 2)
p1 <- p1 + theme_bw()
p1

现在我想用leaflet R包重现相同的情节。

library(leaflet)

leaflet(data = map_data) %>% 
  setView(lng = -77.0167, lat = 38.8833, zoom = 4) %>% 
  addTiles()

如何在rate版本中map_data作为leaflet geom_polygon的地图ggplot2数据框注释{{1}}?

1 个答案:

答案 0 :(得分:3)

也许这是一种出发点:

mapStates = map("state", fill = TRUE, plot = FALSE)
rates <- cut_number(unemp$rate[match(sub("(.*?):.*", "\\1", mapStates$names), unemp$region)], 5) 

leaflet(data = mapStates) %>% addTiles() %>%
      addPolygons(fillColor = brewer_pal(palette = "Set1")(8)[as.numeric(rates)], stroke = FALSE) %>%
      addLegend(colors = brewer_pal(palette = "Set1")(nlevels(rates)), labels = levels(rates), opacity = .2) 

enter image description here

添加:

关于您的其他问题:

library(raster)
pakistan.adm2.spdf <- getData("GADM", country = "Pakistan", level = 2)
rates <- cut_number(unemployment.df$unemployment[match(pakistan.adm2.spdf@data$NAME_2, unemployment.df$id)], 5)
leaflet(pakistan.adm2.spdf) %>% addTiles() %>% 
  addPolygons(fillColor = brewer_pal(palette = "PuRd")(nlevels(rates))[as.numeric(rates)], stroke = FALSE, fillOpacity = .6) %>% 
  addLegend(colors = brewer_pal(palette = "PuRd")(nlevels(rates)), labels = levels(rates), opacity = .6) %>%
  setView(lng = 69.374268, lat = 30.028617, zoom = 5)

enter image description here