[英]add colorFactor palette to mapview object
The aim is to provide fixed colors to factor values.目的是为因子值提供固定的 colors。 I struggle applying a colorFactor scale to a mapview object. However, the palette does not seem to match zcol.我很难将 colorFactor 比例应用于 mapview object。但是,调色板似乎与 zcol 不匹配。
I tried the following, similar to a leaflet map.我尝试了以下,类似于 leaflet map。
library(mapview)
colors <- colorFactor(palette = c("Red", "Green", "Blue"),
levels = c("Oberfranken","Mittelfranken", "Unterfranken"))
mapview(franconia, zcol = "district",col.regions=colors)
I get the following error-message:我收到以下错误消息:
1: In col.regions(nregions) : Some values were outside the color
scale and will be treated as NA
Any help on that?有什么帮助吗?
the following would work on leaflet, but does not make use of mapview.以下将适用于 leaflet,但不使用 mapview。
franconia %>% leaflet() %>% addTiles() %>% addPolygons(fillColor = ~colors(district))
I couldn't figure out how to use Beni's answer to specify which colour I wanted to apply to specific features on the map.我不知道如何使用贝尼的回答来指定我想将哪种颜色应用于 map 上的特定功能。
Turns out that colorFactor
returns a function. You need to supply the field you want to use to colour the features:结果是colorFactor
返回 function。您需要提供要用于为要素着色的字段:
library('sf')
library('leaflet')
library('mapview')
# Read in shapefile and keep the first three features
ncShp <- st_read(system.file("shape/nc.shp", package="sf"))[1:3, ]
ncShp
# Simple feature collection with 3 features and 14 fields
# Geometry type: MULTIPOLYGON
# Dimension: XY
# Bounding box: xmin: -81.74107 ymin: 36.23388 xmax: -80.43531 ymax: 36.58965
# Geodetic CRS: NAD27
# AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID BIR74 SID74 NWBIR74 BIR79 SID79 NWBIR79 geometry
# 1 0.114 1.442 1825 1825 Ashe 37009 37009 5 1091 1 10 1364 0 19 MULTIPOLYGON (((-81.47276 3...
# 2 0.061 1.231 1827 1827 Alleghany 37005 37005 3 487 0 10 542 3 12 MULTIPOLYGON (((-81.23989 3...
# 3 0.143 1.630 1828 1828 Surry 37171 37171 86 3188 5 208 3616 6 260 MULTIPOLYGON (((-80.45634 3...
cols <- c('red', 'green', 'blue')
# Colour our features sequentially based on the NAME field
ncShp$NAME
# [1] "Ashe" "Alleghany" "Surry"
# Ashe will be red, Alleghany will be green, Surry will be blue
colPal <- leaflet::colorFactor(palette = cols, levels = ncShp$NAME)
# Note: use levels(ncShp$NAME) if it's already a factor
# Send it to mapview
mapview::mapview(ncShp, zcol='NAME', col.regions=colPal(ncShp$NAME))
mapview::mapviewColors seems to do the trick: mapview::mapviewColors 似乎可以解决问题:
library(mapview)
colors <- mapviewColors(x=franconia,
zcol = "district",
colors = c("Red", "Green", "Blue"),
at = c("Oberfranken","Mittelfranken", "Unterfranken"))
mapview(franconia, zcol = "district",col.regions = colors)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.