2016-12-24 71 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

很高兴工作。 –