使用 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