Kira Tebbe
Kira Tebbe

Reputation: 586

Leaflet for R: a legend for binary variables

So I've successfully added a legend to my leaflet map, and have a special case for binary variables. However, I want the legend to look better for these binary variables. This problem is embedded within a larger Shiny application, but I'll distill it:

dat <- data.frame("lat"=c(28.8,28.7,28.6,28.5),
                  "lon"=c(77.1,77.2,77.3,77.4),
                  "hiv"=c(0,0,1,1))
colorBy <- "hiv" #just in this example
colorData <- dat[,colorBy]
if(length(unique(colorData)) == 2) pal <- colorBin(c("black","red"), colorData, 2, pretty=F )
else pal <- colorBin(c("red","black"), colorData, 5, pretty=F)

leaflet(dat) %>% 
 addTiles() %>%
  addCircleMarkers(~lon, ~lat, stroke=F,
                   fillOpacity = .6, color = coloring(), radius=radii) %>%
  addLegend("bottomright", pal=pal, values=colorData,
            title=colorBy, opacity=1, layerId="legend")

Right now, the map and legend look like this:Map with binary legend

However, I really want to it have "0" and "1" next to the colors, instead of "0.0-0.5" and "0.5-1.0". Anyone have any idea how to customize it like this?

Upvotes: 3

Views: 1205

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26248

Use colorFactor() instead of colorBin(). colorFactor will keep the levels of the data, i.e. 0 and 1. colorBin is cutting your data into two bins, 0 - 0.5 and 0.5 - 1

library(leaflet)

dat <- data.frame("lat"=c(28.8,28.7,28.6,28.5),
                  "lon"=c(77.1,77.2,77.3,77.4),
                  "hiv"=c(0,0,1,1))
colorBy <- "hiv" #just in this example
colorData <- dat[,colorBy]
if(length(unique(colorData)) == 2){
  pal <- colorFactor(c("black","red"), colorData)
}else{
  pal <- colorFactor(c("red","black"), colorData)
}

leaflet(dat) %>% 
  addTiles() %>%
  addCircleMarkers(~lon, ~lat, stroke=F,
                   fillOpacity = .6, color = "black") %>%
  addLegend("bottomright", pal=pal, values=colorData,
            title=colorBy, opacity=1, layerId="legend")

enter image description here

Upvotes: 1

Related Questions