I want to make a geojson file small/less detailed to speeden up a R Plotly choropleth plot. This is a reproducible plot with the original geojson file:
library(rjson)
library(plotly)
geojson <- rjson::fromJSON(file='https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_DEU_0.json')
#geojson <- geojson2
length(geojson$features)
bl <- sapply(1:length(geojson$features),function(i){geojson$features[i][[1]]$properties$COUNTRY})
for(i in 1:length(geojson$features)){
geojson$features[[i]]$regio <- geojson$features[i][[1]]$properties$COUNTRY
}
Qkreis <- data.frame(regio = bl,
zeroy = rep(0,length(geojson$features))
)
names(Qkreis)[1] <- 'regio'
g <- list(
fitbounds = "locations",
projection = list(type = 'mercator'),
visible = FALSE
)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=geojson,
locations=Qkreis[,'regio'],
text=Qkreis[,'regio'],
z=Qkreis[, 'zeroy'],
colors = c('white','#ed6a12'),
showscale=T,
marker = list(line=list(color='grey',width=0.25)),
featureidkey = 'regio',
geo = 'geo'
)
fig <- fig %>% layout(
geo = g
)
fig
Then I simplify it with rmapshaper (need to convert it to sf and back to geojson) and put the new object into the 2nd line of the code above. But now the plot gets inverted.
library(geojsonsf)
library(rmapshaper)
library(sf)
geosf <- geojson_sf('https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_DEU_0.json')
substr(geosf, 1, 200)
geosf_simpl <- ms_simplify(geosf, keep = 0.001,
keep_shapes = FALSE)
#geoback <- sf_geojson(geosf)
geoback <- sf_geojson(geosf_simpl)
substr(geoback, 1, 200)
geojson2 <- rjson::fromJSON(geoback)
substr(geojson2, 1, 200)
Why, how can I fix it?
I already found out that the problem does not directly happen during simplifying, but at or before choropleth: the normal R plot does not get inverted:
plot(geosf['COUNTRY'])
plot(geosf_simpl['COUNTRY'])
geosf2 <- geojson_sf(geoback)
plot(geosf2['COUNTRY'])
But where and why does the inversion in or before choropleth happen?
solved: the problem is that ms_simplify of rmapshaper lists the geo coordinates clockwise, but choropleth needs them counterclockwise. You need to reverse the sequence of coordinates, e.g. like this:
Then you get correct choropleth plot: