เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้าง Color Palette ด้วย colorFactor

จนถึงตอนนี้เราใช้สีเพื่อปรับแต่งสไตล์ของแผนที่เท่านั้น ด้วย colorFactor() เราสามารถสร้าง color palette ที่กำหนดสีให้กับแต่ละระดับของตัวแปรประเภท factor ได้

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

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

ทำไมเราอาจไม่ต้องการใช้ color palette นี้?

หากสนใจใช้ตัวแปรแบบต่อเนื่องในการกำหนดสีบนแผนที่ ลองดูที่ colorNumeric()

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

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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Interactive Maps with leaflet in R

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง color palette ชื่อ pal สำหรับค่าของ sector_label โดยใช้ colorFactor() ด้วยสี "red", "blue" และ "#9b4a11"
  • เพิ่ม circle markers ที่กำหนดสีของมหาวิทยาลัยโดยใช้ 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
แก้ไขและรันโค้ด