使用 colorFactor 建立調色盤
到目前為止,我們只用顏色來客製化地圖的樣式。透過 colorFactor(),你可以建立一個調色盤,將顏色對應到因子變數的各層級。
pal <-
colorFactor(palette = c("blue", "red", "green"),
levels = c("Public", "Private", "For-Profit"))
m %>%
addCircleMarkers(color = ~pal(sector_label))
為什麼我們可能不想使用這組特定的調色盤?
如果你想用連續變數來著色地圖,請參考 colorNumeric()。
pal <- colorNumeric(palette = "RdBu", domain = c(25:50))
ipeds %>%
leaflet() %>%
addProviderTiles("CartoDB") %>%
addCircleMarkers(radius = 2, color = ~pal(lat))
本練習屬於課程
在 R 中使用 leaflet 製作互動式地圖
練習說明
- 使用
colorFactor()為sector_label的值建立名為pal的調色盤,使用 "red"、"blue" 和 "#9b4a11"。 - 新增圓形標記,使用
pal()和sector_label的值來為各學校著色。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Make a color palette called pal for the values of `sector_label` using `colorFactor()`
# Colors should be: "red", "blue", and "#9b4a11" for "Public", "Private", and "For-Profit" colleges, respectively
pal <- ___(palette = c("red", "blue", ___),
levels = c("Public", "Private", "For-Profit"))
# Add circle markers that color colleges using pal() and the values of sector_label
map2 <-
map %>%
addCircleMarkers(data = ca, radius = 2,
color = ~pal(sector_label),
label = ~paste0(name, " (", sector_label, ")"))
# Print map2
map2