Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple `addCircleMarkers` layers using Leaflet in R?

Tags:

r

leaflet

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?

like image 515
tumultous_rooster Avatar asked Feb 10 '23 08:02

tumultous_rooster


1 Answers

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 leaflet sample with multiple layers addCircleMarkers()

like image 109
symbolrush Avatar answered Feb 11 '23 21:02

symbolrush