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:
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?
答案 0 :(得分:1)
使用colorFactor()
代替colorBin()
。 colorFactor
会保留数据级别,即0
和1
。 colorBin
正在将您的数据分成两个分类:0 - 0.5
和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")