Bắt đầu ngayBắt đầu miễn phí

Tạo bảng màu bằng colorFactor

Đến giờ bạn mới chỉ dùng màu sắc để tùy chỉnh kiểu hiển thị của bản đồ. Với colorFactor() bạn có thể tạo một bảng màu gán màu cho từng mức của một biến kiểu factor.

pal <- 
   colorFactor(palette = c("blue", "red", "green"), 
               levels = c("Public", "Private", "For-Profit"))

m %>% 
    addCircleMarkers(color = ~pal(sector_label))

Vì sao chúng ta có thể không muốn dùng bảng màu cụ thể này?

Nếu bạn muốn dùng một biến liên tục để tô màu bản đồ, hãy xem colorNumeric().

pal <- colorNumeric(palette = "RdBu", domain = c(25:50))

ipeds %>% 
    leaflet() %>% 
        addProviderTiles("CartoDB")  %>% 
        addCircleMarkers(radius = 2, color = ~pal(lat))

Bài tập này là một phần của khóa học

Bản đồ tương tác với leaflet trong R

Xem khóa học

Hướng dẫn bài tập

  • Tạo một bảng màu tên pal cho các giá trị của sector_label bằng colorFactor() với "red", blue", và "#9b4a11".
  • Thêm các marker hình tròn và tô màu các trường đại học bằng pal() với các giá trị của sector_label.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# 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
Chỉnh sửa và Chạy Mã