tumultous_rooster
tumultous_rooster

Reputation: 12550

Multiple `addCircleMarkers` layers using Leaflet in R?

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?

Upvotes: 4

Views: 11530

Answers (1)

symbolrush
symbolrush

Reputation: 7457

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()

Upvotes: 10

Related Questions