如何创建美国各县的传单等值线图

How to create a leaflet choropleth map of US counties

使用下面的代码,我得到了包含美国县数据的数据框

library(raster)
library(leaflet)
library(tidyverse)

# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)

我的目标是创建一个 Avg_yield 的交互式传单等值线图,所以首先我要加强我的美国多边形数据

library(rgeos)
library(maptools)
library(ggplot2)
states.shp.f <- fortify(USA, region = "NAME_2")

然后我对我的数据集进行子集化并将其与强化的合并:

mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"id"

## merge shape file with data
merge.shp.coef <- merge(states.shp.f, mydata2, by = "id")

但现在我有一个包含每个县名很多次的数据集,而且一些县有不同的 Avg_yield 值。处理这些数据以使用传单代码的正确方法是什么:

leaflet() %>% 
  addProviderTiles("OpenStreetMap.Mapnik") %>%
  setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
  addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
              fillColor = ~mypal(mydata$Avg_yield),
              popup = paste("Region: ", USA$NAME_2, "<br>",
                            "Avg_yield: ", mydata$Avg_yield, "<br>")) %>%
  addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
            title = "Avg_yield",
            opacity = 1)

这样做的最佳方法是将多边形对象转换为 sf 对象 st_as_sf()

这里有一个工作示例: (我确实为多边形使用了一些其他数据,我认为你的太精确并且需要大量资源,而且我让它与 shiny 一起使用)

library(leaflet)
library(tidyverse)
library(ggplot2)
library(sf)
library(shiny)

USA <- st_read(dsn = '[your path]/cb_2018_us_county_500k.shp')

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)

states_sf <- st_as_sf(USA)

mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"NAME"

## merge shape file with data
states_sf_coef <- left_join(states_sf, mydata2, by = "NAME")


ui <- fluidPage(

  leafletOutput("map", height = "100vh")
)

server <- function(input, output, session) {

  bins <- c(0, 5, 10, 15, 20, 25, 30, 35, 40)
  mypal <- colorBin("YlOrRd", domain = states_sf_coef$Avg_yield, bins = bins)

  #Sortie map
  output$map <- renderLeaflet({
    leaflet()%>%
      addProviderTiles("OpenStreetMap.Mapnik")%>%
      setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
      addPolygons(
        data = states_sf_coef,
        fillColor = ~mypal(states_sf_coef$Avg_yield),
        stroke = FALSE,
        smoothFactor = 0.2,
        fillOpacity = 0.3,
        popup = paste("Region: ", states_sf_coef$NAME_2, "<br>",
                      "Avg_yield: ", states_sf_coef$Avg_yield, "<br>"))%>%
      addLegend(position = "bottomleft",
                pal = mypal,
                values = states_sf_coef$Avg_yield,
                title = "Avg_yield",
                opacity = 1)
  })

}

# Create Shiny app ----
shinyApp(ui = ui, server = server)