2015-08-20 74 views
0

我使用rCharts單張地圖在R上的地圖上顯示多邊形。 使用Leaflet的geoJson我創建了一些多邊形並將它們添加到地圖中。但是,這些多邊形會填充默認的藍色。我試圖給他們一種不同的顏色,但沒有成功。 舉個例子,我使用了下面的JSON,在geojson.io中測試了它,並且它變成了綠色,但是R包仍然以藍色繪製它,我該如何強制顏色?rCharts GeoJSON - 更改多邊形的填充顏色

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 

回答

1

雖然rCharts執行是好的,RStudio的leaflet包基於htmlwidgets得多全功能和強大的。如果你可以使用它,這裏是一個答案。請注意,不需要做任何事情。 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' 
)