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