我正在用R中的"leaflet“制作一张华盛顿特区人口的交互式地图,我想用不同的颜色来区分这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"))本质上,我想为每个社区分配不同的颜色,就像上面文本中尝试的那样,但我遗漏了一些东西。如果你有想法,请分享。
发布于 2016-12-24 13:48:37
看起来您尚未将您创建的调色板连接到数据和图例。试着做一些类似的事情:
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‘参数将所有层绑定在一起。
https://stackoverflow.com/questions/41310344
复制相似问题