我使用rCharts Leaflet地图在R上的地图上显示多边形。 使用Leaflet的geoJson我创建了一些多边形并将它们添加到地图中。但是,这些多边形填充了默认的蓝色。我试图给他们一个不同的颜色,但没有成功。 举个例子,我使用了下面的JSON,在geojson.io中进行了测试,然后它显示为绿色,但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
答案 0 :(得分:1)
虽然rCharts
实施很好,但基于leaflet
的RStudio htmlwidgets
包的功能更强大,功能更强大。如果您可以使用它,这是一个答案。注意,不需要做任何事情。 leaflet
会在fill
中提取geoJSON
。
# 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'
)