Creating a Color Palette using colorFactor
So far we have only used color to customize the style of our map. With colorFactor()
we can create a color palette that maps colors the levels of a factor variable.
pal <-
colorFactor(palette = c("blue", "red", "green"),
levels = c("Public", "Private", "For-Profit"))
m %>%
addCircleMarkers(color = ~pal(sector_label))
Why might we not want to use this particular color palette?
If you are interested in using a continuous variable to color a map see colorNumeric()
.
pal <- colorNumeric(palette = "RdBu", domain = c(25:50))
ipeds %>%
leaflet() %>%
addProviderTiles("CartoDB") %>%
addCircleMarkers(radius = 2, color = ~pal(lat))
This is a part of the course
“Interactive Maps with leaflet in R”
Exercise instructions
- Make a color palette called
pal
for the values ofsector_label
usingcolorFactor()
using "red", blue", and "#9b4a11". - Add circle markers that color colleges using
pal()
and the values ofsector_label
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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
This exercise is part of the course
Interactive Maps with leaflet in R
Learn how to produce interactive web maps with ease using leaflet.
In chapter 2 students will build on the leaflet map they created in chapter 1 to create an interactive web map of every four year college in California. After plotting hundreds of points on an interactive leaflet map, students will learn to customize the markers on their leaflet map. This chapter will also how to color code markers based on a factor variable.
Exercise 1: Introduction to IPEDS DataExercise 2: Cleaning up the Base MapExercise 3: Exploring the IPEDS DataExercise 4: Exploring the IPEDS Data IIExercise 5: Mapping California CollegesExercise 6: California CollegesExercise 7: The City of CollegesExercise 8: Circle MarkersExercise 9: Labels and Pop-upsExercise 10: Making our Map PopExercise 11: What is California's Northernmost College?Exercise 12: Building a Better Pop-upExercise 13: Swapping Popups for LabelsExercise 14: Color Coding CollegesExercise 15: Creating a Color Palette using colorFactorExercise 16: A Legendary MapWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.