echarty icon indicating copy to clipboard operation
echarty copied to clipboard

Choropleth on categorical values

Open helgasoft opened this issue 3 years ago • 3 comments

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.

helgasoft avatar Sep 08 '22 20:09 helgasoft

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

lgnbhl avatar Sep 09 '22 08:09 lgnbhl

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.

helgasoft avatar Sep 09 '22 18:09 helgasoft

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

lgnbhl avatar Sep 10 '22 09:09 lgnbhl