我使用rCharts传单地图显示多边形在地图上的R。使用传单的geoJson,我创建了一些多边形,并将它们添加到地图上。然而,这些多边形是用默认的蓝色填充的。我试着给它们换一种颜色,但没有成功。例如,我使用了以下JSON,并在geojson中进行了测试。它显示为绿色,但是R包仍然将其绘制为蓝色,我如何执行该颜色?
JSON:{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"stroke": "#555555",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#00f900",
"fill-opacity": 0.5
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-74.06982421875,
40.64730356252251
],
[
-74.06982421875,
40.79717741518769
],
[
-73.80615234375,
40.79717741518769
],
[
-73.80615234375,
40.64730356252251
],
[
-74.06982421875,
40.64730356252251
]
]
]
}
}
]
}
R: jsonx <- (JSON above)
polys = RJSONIO::fromJSON(jsonX)
map.center <- c(38,-95)
myMap<-Leaflet$new()
myMap$setView(map.center, 4)
myMap$tileLayer(provider = "Esri.WorldGrayCanvas")
myMap$geoJson(polys)
myMap$set(dom = 'myChart2')
myMap
虽然rCharts
的实现很好,但RStudio基于htmlwidgets
的leaflet
包功能更全面,更健壮。如果你可以用它来代替,这里有一个答案。注意,什么都不需要做。leaflet
将拾取geoJSON
中的fill
。
# uncomment to install the most recent from github
# devtools::install_github("rstudio/leaflet")
# or older cran #install.packages("leaflet")
library(leaflet)
gj <- '
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"stroke": "#555555",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#00f900",
"fill-opacity": 0.5
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-74.06982421875,
40.64730356252251
],
[
-74.06982421875,
40.79717741518769
],
[
-73.80615234375,
40.79717741518769
],
[
-73.80615234375,
40.64730356252251
],
[
-74.06982421875,
40.64730356252251
]
]
]
}
}
]
}
'
leaflet() %>%
addTiles() %>%
setView( -74.1, 40.7, zoom = 10) %>%
addGeoJSON( gj )
# to show fill works let's change it with gsub
leaflet() %>%
addTiles() %>%
setView( -74.1, 40.7, zoom = 10) %>%
addGeoJSON(
gsub(
x = gj
,pattern = '(\"fill": \"#00f900\",)'
,replacement = ""
)
# demo addGeoJSON fillColor argument
,fillColor = 'green'
)