Get Started

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”

View Course

Exercise instructions

  • Make a color palette called pal for the values of sector_label using colorFactor() using "red", blue", and "#9b4a11".
  • Add circle markers that color colleges using pal() and the values of sector_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

BeginnerSkill Level
4.6+
5 reviews

Learn how to produce interactive web maps with ease using leaflet.

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free