我正在使用R中的“传单”制作D.C.地区人口的互动地图,我想用不同的颜色来区分7个不同的社区。我的变量是:地址,社区,性别和名称(对于弹出窗口)。我使用了TrendCt和Ripples中的一些代码。
我如何调整我的代码以显示不同社区的不同颜色,甚至可能如何更改阴影以区分社区中的性别?
这是我的代码:
###########################################################################
#################### 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 :(得分:7)
看起来您没有将创建的调色板连接到数据和图例。尝试以下方面:
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”参数将所有图层绑定在一起。