通过使用 R 中的纬度和经度坐标将颜色段添加到地图上的位置

Add color segments to location on a map plot by using lat and lng coordinates in R

我的数据集有 4 列,分别是 station_namestation_latstation_lngcount。这是我的数据集的例子。

start_stations <-
  data.frame(
    station = c("StreeterDr", "MichiganAve", "WellsSt"),
    lat = c(41.89228, 41.90096, 41.91213),
    lng = c(-87.61204,-87.62378,-87.63466),
    n = c(23000, 56780, 34520)
  )

我需要根据站点(位置)的计数使用这些坐标和颜色变化绘制地图,并使用名称和计数标记每个位置。我试过这段代码,但出现错误。

install.packages(c("leaflet", "sp")) 
library(leaflet)
library(sp)
install.packages("sf")
library(sf)

lon <- start_stations$lng
lat <- start_stations$lat
name <- start_stations$station
count <- start_stations$n
dfs <- as.data.frame(cbind(lon,lat,name,count))

dfs<- st_as_sf(dfs)

getColor <- function(dfs) {
  sapply(dfs$count, function(count) {
  if(count <= 20000) {
    "green"
  } else if(count <= 30000) {
    "orange"
  } else {
    "red"
  } })
}

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(top100_start_station_cordinates)
)

leaflet(dfs) %>% addTiles() %>%
  addAwesomeMarkers(~lon, ~lat, icon=icons, popup = ~as.character(name), label=~as.character(count))

使用st_as_sf时需要定义coords

dfs <- sf::st_as_sf(dfs, coords = c("lon","lat"))

# But you might also want to go ahead and define the projection here too. 
# If so, then add in the crs argument.
# dfs <- sf::st_as_sf(dfs, coords = c("lon", "lat"), crs = 4326)

输出

Simple feature collection with 3 features and 2 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -87.63466 ymin: 41.89228 xmax: -87.61204 ymax: 41.91213
CRS:           NA
         name count                   geometry
1  StreeterDr 23000 POINT (-87.61204 41.89228)
2 MichiganAve 56780 POINT (-87.62378 41.90096)
3     WellsSt 34520 POINT (-87.63466 41.91213)

然后,您应该能够 运行 您剩余的代码并获得传单输出。