My data set has 4 columns which are station_name
, station_lat
, station_lng
, and count
. This is the example of my data set.
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)
)
I need to plot a map using these coordinates and color variations to stations (locations) according to its count and label each location using name and count. I tried this code, and an error occurred.
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))
CodePudding user response:
You need to define the coords
when using st_as_sf
.
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)
Output
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)
Then, you should be able to run your remaining code and get the leaflet output.