Flyer for R: Legend for Binary Variables

So, I have successfully added a legend to my booklet map and have a special case for binary variables. However, I want the legend to look better for these binary variables. This issue is built into the larger Shiny app, but I'll overtake 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 looks like this: Binary Legend Card

However, I really want it to have "0" and "1" next to the colors, instead of "0.0-0.5" and "0.5-1.0". Does anyone know how to set it up?

+3


source to share


1 answer


Use colorFactor()

instead colorBin()

. colorFactor

will support data layers, i.e. 0

and 1

. colorBin

splits your data into two bins, 0 - 0.5

and0.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

+1


source







All Articles