Multiple `addCircleMarkers` layers using Leaflet i

2019-05-27 12:28发布

问题:

When using Leaflet in R, I assumed that plotting layers (ala ggplot) would be effective:

 m <- leaflet() %>%
      addTiles() %>%
      addCircleMarkers(lat=subset(DF, outcome=='W')$lat, lng=subset(DF, outcome=='W')$lon, color= "red") %>%
      addCircleMarkers(lat=subset(DF, outcome=='L')$lat, lng=subset(DF, outcome=='L')$lon, color= "blue") 

I had assumed that this would give me two different colored circle markers, red markers for those records that had 'W' outcomes, and blue markers for records that had 'L' outcomes.

Instead, I don't get any map at all.

How can I pipe multiple addCircleMarkers in sequence using Leaflet in R?

回答1:

Pipelining is straight forward. The following code works for me.

leaflet() %>% 
  addTiles() %>% 
  addCircleMarkers(lng = 9, lat = 47, color = 'red') %>% 
  addCircleMarkers(lng = 8.5, lat = 47.5, color = 'blue')

Also your example code works fine with a sample data frame:

DF <- data.frame(lat = c(47,48), lon = c(8,9), outcome = c("W", "L"))
leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lat=subset(DF, outcome=='W')$lat, lng=subset(DF,outcome=='W')$lon, 
    color= "red") %>%
  addCircleMarkers(
    lat=subset(DF, outcome=='L')$lat, lng=subset(DF, outcome=='L')$lon, 
    color= "blue")

This gives the following map



标签: r leaflet