helgasoft / echarty

Minimal R/Shiny Interface to ECharts.js
https://helgasoft.github.io/echarty/
88 stars 3 forks source link

Choropleth on categorical values #14

Closed helgasoft closed 2 years ago

helgasoft commented 2 years ago

Do categorical values work for choropleth maps? asked here by @lgnbhl ECharts seems to ignore non-numerical categories in piecewise choropleths. But numerical categories work.

cns <- countrycode::codelist$country.name.en
cns <- data.frame(
    country = cns,
#   category = sample(LETTERS[1:4], length(cns), replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05))
    category = sample(1:4, length(cns), replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05))
)
# set colors for categories
colors <- c('#8b0069','#75c165', '#ce5c5c', '#fbc357')
pieces <- lapply(unique(cns$category), function(x) { 
    list(value= x, label= LETTERS[x], color= colors[x]) 
})

library(echarty)
cns |> ec.init(load= 'world', visualMap= list(type= 'piecewise', pieces=pieces) )

image if you like this solution, please consider granting a Github star ⭐ to echarty.

lgnbhl commented 2 years ago

Thank you for the explanation and for the solution using echarty :)

helgasoft commented 2 years ago

Felix, maybe this is what you want?

library(dplyr)
cns <- countrycode::codelist$country.name.en
cns <- data.frame(
    country = cns,
    category = sample(LETTERS[1:4], length(cns), replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05))
) |> 
  mutate(numbas= match(category,LETTERS)) |>   # keep them in sync
  relocate(numbas, .after= country) # default Y-axis is the second column
palet <- c('#8b0069','#75c165', '#ce5c5c', '#fbc357')
fmtr <-  htmlwidgets::JS("function (x) { return x.data[0]+'<br>cat: <b>'+x.data[2]; }")

library(echarty)
cns |> ec.init(load= 'world', 
    tooltip= list(show= TRUE),
    visualMap= list(type= 'piecewise', 
        inRange= list(color= palet),
        outOfRange= list(color= 'grey'),
        categories= LETTERS[1:4], 
            dimension= 3)) |>   # position of 'category' column in cns(country, numbas, category)
ec.upd({ series[[1]]$tooltip <- list(formatter= fmtr) })  # update preset

image

if you like this solution, please consider granting a Github star ⭐ to echarty.

lgnbhl commented 2 years ago

Thanks you so much! Yes, it is exactly what I wanted.

However, I am not able to reproduce it with the R package "echarts4r": https://github.com/JohnCoene/echarts4r/issues/460#issuecomment-1242675482