R Leaflet图例:指定顺序而非按字母排序

5
我为r leaflet代码添加了图例,输出结果如下:

enter image description here

我希望顺序为:
  • 绿色 "超过 66%"
  • 橙色 "介于 33% 和 66% 之间"
  • 红色 "少于 33%"

代码

sep <- read.csv("31R_SEP_assets_csv - Copy.csv")

Sub1 <- sep[grep("SEP.12", names(sep))]
sep$newCol <- 100*rowSums(Sub1)/rowSums(sep[4:7])

# create a new grouping variable
Percent_SEP12_Assets <- ifelse(sep[,8] <= 33, "Less than 33%", ifelse(sep[,8] >= 66, "More than 66%", "Between 33% and 66%"))

Color_Assets <- colorFactor(c("darkgreen","darkorange","darkred"),
                               levels = Percent_SEP12_Assets,ordered=FALSE)

leaflet(data = sep[]) %>% 
  setView(lng = mean(sep$Longitude), lat = mean(sep$Latitude), zoom = 12) %>% addTiles()  %>%
  addCircleMarkers(~Longitude, ~Latitude,  color = ~Color_Assets(Percent_SEP12_Assets),  popup = ~as.character(paste(Site, Percent_SEP12_Assets , sep=", "))) %>%
  addLegend("bottomright", pal = Color_Assets, values = Percent_SEP12_Assets, title = "SEP 12 Installs")

dput(sep)

structure(list(Site = structure(1:5, .Label = c("Staten Island\\31R001", 
"Staten Island\\31R002", "Staten Island\\31R003", "Staten Island\\31R004", 
"Staten Island\\31R005"), class = "factor"), Latitude = c(40.508874, 
40.577256, 40.520825, 40.552373, 40.529697), Longitude = c(-74.244048, 
-74.100135, -74.211845, -74.195516, -74.187532), Windows.SEP.11 = c(63L, 
174L, 11L, 85L, 163L), Mac.SEP.11 = c(0L, 1L, 4L, 0L, 0L), Windows.SEP.12 = c(124L, 
185L, 9L, 75L, 23L), Mac.SEP.12 = c(0L, 1L, 32L, 1L, 0L), newCol = c(66.3101604278075, 
51.5235457063712, 73.2142857142857, 47.2049689440994, 12.3655913978495
)), .Names = c("Site", "Latitude", "Longitude", "Windows.SEP.11", 
"Mac.SEP.11", "Windows.SEP.12", "Mac.SEP.12", "newCol"), row.names = c(NA, 
-5L), class = "data.frame")

谢谢!


你需要将图例标签设置为因子而不是文本,然后它就可以工作了。 - John Paul
dput的作用是什么? - hrbrmstr
@hrbrmstr,这是九月的事情,我已经改正了帖子。 - Rhonda
@JohnPaul,我认为标签是因子,即 values = Percent_SEP12_Assets - Rhonda
1
colorFactor有一个ordered参数... - hrbrmstr
@hrbrmstr 我添加了 ordered,即 Color_Assets <- colorFactor(c("darkgreen","darkorange","darkred"), levels = Percent_SEP12_Assets, ordered=FALSE),但输出仍然相同。 - Rhonda
1个回答

5
# create a new grouping variable
Percent_SEP12_Assets <- factor((sep[,8] > 33) + (sep[, 8] >= 66), labels = c("Less than 33%", "Between 33% and 66%", "More than 66%"))

Color_Assets <- colorFactor(c("darkred","darkorange","darkgreen"),
                           levels = Percent_SEP12_Assets,ordered=FALSE)

需要具有顺序的因子。我还用逻辑表达式的总和替换了ifelse


我尝试了,但现在地图和图例的颜色方案是相反的,即少于33%的部分是绿色而不是红色,超过66%的部分是红色而不是绿色.....我会进行研究..... - Rhonda
1
@SohniMahiwal,你需要在下一行中交换颜色。请查看编辑。 - Nick Kennedy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接