简体   繁体   中英

How to plot country-based choropleths using leaflet R

World boundaries geo.json downloaded from here. https://github.com/johan/world.geo.json

I am trying to highlight 3 countries(in a world map view) and paint them in gradient color according to numbers of projects in that country.

Here're my steps:

Firstly download world boundary geo.json file and read it as the basemap; Then I try highlight the country polygons in my data. However it turns out that All the world countries are ramdomly colored and labeled by the 3 countries' information. Is it geo dataframe subsetting issue?

WorldCountry <-geojsonio::geojson_read("./GeoData/countries.geo.json", what = "sp")

#Dataframe for choropleth map
Country <- c("Bulgaria","Pakistan","Turkey")
Projects <- c(2,1,6)
data <- data.frame(Country,Projects)

#basemap
Map <- leaflet(WorldCountry) %>% addTiles() %>% addPolygons()

#set bin and color for choropleth map
bins <- c(0,1,2,3,4,5,6,7,8,9,10,Inf)
pal <- colorBin("YlOrRd", domain = data$Projects, bins = bins)

#set labels
labels <- sprintf(
  "<strong>%s</strong><br/>%g projects <sup></sup>",
  data$Country, data$Projects) %>% lapply(htmltools::HTML)

#add polygons,labels and mouse over effect
Map %>% addPolygons(
  fillColor = ~pal(data$Projects),
  weight = 2,
  opacity = 1,
  color = 'white',
  dashArray = '3',
  fillOpacity = 0.7,
  highlight = highlightOptions(
     weight = 5,
    color = "#666",
    dashArray = "",
    fillOpacity = 0.7,
    bringToFront = TRUE),
  label = labels,
  labelOptions = labelOptions(
    style = list("font-weight" = "normal", padding = "3px 8px"),
    textsize = "15px",
    direction = "auto")
)

I am expecting something like this:

在此处输入图片说明

This will do the trick! Subset the WorldCountry using:

data_Map <- WorldCountry[WorldCountry$id %in% data$Country, ]
Map <- leaflet(data_Map) %>% addTiles() %>% addPolygons()

The subset would be with WorldCountry$name

data_Map <- WorldCountry[WorldCountry$name %in% data$Country, ]

Map <- leaflet(data_Map) %>% addTiles() %>% addPolygons(
  fillColor = ~pal(data$Projects),
  weight = 2,
  opacity = 1,
  color = 'white',
  dashArray = '3',
  fillOpacity = 0.7,
  highlight = highlightOptions(
    weight = 5,
    color = "#666",
    dashArray = "",
    fillOpacity = 0.7,
    bringToFront = TRUE),
  label = labels,
  labelOptions = labelOptions(
    style = list("font-weight" = "normal", padding = "3px 8px"),
    textsize = "15px",
    direction = "auto")
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM