I'm trying to plot a map of Colombia's provinces and a factor variable with 8 levels, I'm using Long-Lat coordinates.
My dataframe looks like this:
> head(df[,c('CODMPIO','Esc2a','Longitud','Latitud')])
# A tibble: 6 x 4
CODMPIO Esc2a Longitud Latitud
<chr> <fct> <dbl> <dbl>
1 05001 4 -75.6 6.25
2 05002 5 -75.4 5.79
3 05004 7 -76.1 6.63
4 05021 5 -75.1 6.38
5 05030 7 -75.7 6.04
6 05031 7 -75.1 6.91
and the geojson has the coordinates and these columns:
$properties
$properties$DPTOMPIO
[1] "05001"
$properties$DPTO_CCDGO
[1] "05"
$properties$MPIO_CCDGO
[1] "001"
$properties$MPIO_CNMBR
[1] "MEDELLÍN"
$properties$MPIO_CCNCT
[1] "05001"
properties$DPTOMPIO
is the same as
df$CODMPIO
Finally, all my code is this
df$Esc2a = factor(df$Esc2a)
df$test = as.numeric(df$Esc2a)
nfactor = length(levels(df$Esc2a))
foo <- brewer.pal(n = nfactor,name = "Set1")
names(foo) = levels(df$Esc2a)
Z_Breaks = function(n){
CUTS = seq(0,1,length.out=n+1)
rep(CUTS,ifelse(CUTS %in% 0:1,1,2))
}
colorScale <- data.frame(z=Z_Breaks(nfactor),
col=rep(foo,each=2),stringsAsFactors=FALSE)
g <- list(
fitbounds = "locations",
visible = FALSE
)
fig <- plot_ly()
fig <- fig %>% add_trace(
data=df,
type="choropleth",
geojson=geojson,
locations= ~CODMPIO,
z=df$test,
colorscale=colorScale,
colorbar=list(tickvals=1:nfactor, ticktext=names(foo)),
featureidkey="properties.DPTOMPIO"
)
fig <- fig %>% layout(
geo = g
)
fig
The first lines were done using the answer on this question How to create a chloropleth map in R Plotly based on a Categorical variable?
I get the following plot
It classifies the factors correctly, when I hover over it shows me the right value and right ID but as you can see it's not colouring as it should only the last row is being correctly coloured (the green one)