2016-12-24 35 views
4

我使用R中的「單張」製作了在D.C.區域內人口的交互式地圖,並且我想使用不同的顏色區分7個不同的社區。我的變量是:地址,社區,性別和名稱(用於彈出窗口)。我使用了TrendCtRipples的一些代碼。使用R中的單張區分顏色使用顏色區分變量

我該如何調整我的代碼以顯示不同社區的不同顏色,甚至我怎麼能改變陰影來區分社區中的性別?

這裏是我的代碼:

########################################################################### 
#################### D.C. Community Map in R ############################## 
########################################################################### 

## Retrieve Data and Download Package 
# Use import data set dropdown menu to import data correctly 
# Community Map.csv 

# Load packages 
library(dplyr) 
library(ggmap) 
library(leaflet) 

# Define new data set 
ysa <- Community.Map 

## Generate dataset with coordinate variables 
## Averages 10 minutes to render on my i5 processor 
ysa %>% 
    mutate(address=paste(gender, sep=", ", ward)) %>% 
    select(address) %>% 
    lapply(function(x){geocode(x, output="latlon")}) %>% 
    as.data.frame %>% 
    cbind(ysa) -> ysa1 

ysa %>% 
    mutate(popup_info=paste(sep = "<br/>", paste0("<b>","<i>", ward,"<i>", "  
    </b>"), name)) %>% 
    mutate(lon=ifelse(is.na(longitude), address.lon, longitude), 
     lat=ifelse(is.na(latitude), address.lat, latitude)) %>% 
    filter(!is.na(lon) & !grepl("CLOSED", ward)) -> ysa2 

# Plot the map 
leaflet(ysa2) %>% 
    addProviderTiles("CartoDB.Positron") %>% 
    addCircleMarkers(lng = ~longitude, 
        lat = ~latitude, 
        radius = 1.5, 
        color = "red", 
        stroke=FALSE, 
        fillOpacity = 0.8, 
        popup = ~popup_info) %>% 
addLegend("bottomright", colors= "red", labels="Community ", title="YSA  
Bounderies by Community") 

我一直在試圖通過使用下面的代碼的顏色來劃分:

# color <- colorFactor(c("blue", "red", "green", "yellow", "brown", "gold", "purple"),  
domain = c("Braddock", "Shenandoah", "Langley", "DC 2nd", "Colonial 1st", 
"Colonial 2nd", "Glenn Dale")) 

從本質上講,我要分配每個社區不同的顏色,喜歡嘗試在上面的文字中,但我錯過了一些東西。請分享,如果你有想法。

+0

'Community.Map'從哪裏來?沒有它,這是無法重現的。 –

回答

5

看起來您沒有將您創建的調色板連接到數據和圖例。嘗試一下:

library(viridis) # My favorite palette for maps 
wardpal <- colorFactor(viridis(7), ysa2$ward) # I'm assuming the variable ward contains the names of the communities. 

leaflet(ysa2) %>% 
    addProviderTiles("CartoDB.Positron") %>% 
    addCircleMarkers(lng = ~longitude, 
         lat = ~latitude, 
         radius = 1.5, 
         fillColor = ~wardpal(ward), 
         stroke=FALSE, 
         fillOpacity = 0.8, 
         popup = ~popup_info) %>% 
    addLegend("bottomright", pal = wardpal, values = ~ward, labels = "Community ", title = "YSA Bounderies by Community") 

您還想要在色彩陰影中編碼性別。您是否嘗試將fillOpacity映射到描述性別分佈的變量(例如,fillOpacity = ~ percent_female)。或者,您可以爲每個社區添加一個單獨的圖層,根據性別流行程度爲每個圖層設置調色板。您可以使用每個addCirlayer調用中的「group」參數將所有圖層連接在一起。

+0

這是非常有用的,並伎倆!我感謝Peter K.我正在測試現在的圖層建議。 –

+0

很高興工作。 –

相關問題