Leaflet for R: a legend for binary variables

时间:2015-07-31 20:34:32

标签: r leaflet legend

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?

1 个答案:

答案 0 :(得分:1)

使用colorFactor()代替colorBin()colorFactor会保留数据级别,即01colorBin正在将您的数据分成两个分类:0 - 0.50.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