簡體   English   中英

帶有 2 個 colors 和自定義斷點的自定義調色板 R leaflet - 連續變量

[英]Custom palette with 2 colors and custom breakpoints in R leaflet - continuous variable

我正在嘗試為我的 leaflet map 創建具有 2 種顏色(紅色和綠色)和自定義斷點的自定義調色板。 目前我使用的是單一的紅色調色板。 我使用colornumeric生成的 Mymap

pal2 <- colorNumeric(palette = "Reds", domain=NULL)

我在我的 leaflet 中使用它作為

leafletProxy("map", data = selecteddata()) %>% #, data = temp2.df ------ took it out/ selecteddata()
  addPolygons(data = temp2.df ,fillColor = ~pal2(selecteddata()),
              highlightOptions = highlightOptions(color = "orange", weight = 2), 
              color = "#BDBDC3",
              fillOpacity = 0.8,
              weight = 1,
              label = ~NAME                
  )

我正在尋找的是在 colors 綠色和紅色中為 map 着色,而不是在綠色處中斷 - +10%、+20%、+35%、+50%、+inf 紅色 -10%、-20%, -35%、-50%、-inf

所需的調色板

我如何實現這一目標?

PS - 我還想在最終顯示中刪除 map 的未着色區域,使其看起來像第二張圖像

當您想要復雜的顏色/斷點時,調色板很棘手。 另一種方法是在數據中添加一個顏色列,然后自己計算適當的 RGB 值。 它需要幾行額外的代碼,但您可以獲得更好的控制:

在此處輸入圖像描述

下面是一個使用所需調色板的最小示例:

library(leaflet)
library(maps)

#Load a map of the US from the 'map' package
shp_map = map("state", fill = TRUE, plot = FALSE)

#Add a made up percentage
shp_map$percentage <- sample(seq(from = -100, to = 50), length(shp_map$names))

#Define the breaks and associated RGB value
vec_breaks <- c(     -100,       -50,       -35,       -20,       -10,         0,        10,        20,        35,        55)
vec_rgb    <- c("#b51224", "#d93e22", "#f5783f", "#ffb15a", "#ffe08d", "#dae88e", "#a1cd6a", "#67ac62", "#15854c", "#005c37") 

#Add a colour column, and put in the appropriate RGB value
for (i in 1:length(shp_map$percentage)) {
    shp_map$colour[i] <- vec_rgb[min(which(vec_breaks > shp_map$percentage[i])) - 1]
}

#Draw map
leaflet(data = shp_map) %>% 
    addPolygons(fillColor = shp_map$colour, stroke = TRUE, fillOpacity = 0.8, color = "black", opacity = 1, weight = 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM