JohnCoene / echarts4r

🐳 ECharts 5 for R
http://echarts4r.john-coene.com/
Other
592 stars 81 forks source link

MULTIPLE CATEGORIES BOX PLOT #253

Open jlejarraga opened 3 years ago

jlejarraga commented 3 years ago

Hi John, many thank for the amazing package, I have the next issue/doubt: I want to plot multiple categories in box-plot like: https://echarts.apache.org/examples/en/editor.html?c=boxplot-multi

Maybe I am wrong but, Currently you can group_by one category and it work well, by contrast, if you by two or more categories it does not work.

Is there any way to group by more than one category? thank you in advance

helgasoft commented 3 years ago

Wow, a good 5-star question 🏆 There may be a more elegant way of doing this, but here is my way.

grps <- list()   # data in 3 groups
for (grp in 1:3) {
  seriesData <- list()
  for (i in 1:18) {
    cate <- runif(10,1,200)
    seriesData <- append(seriesData, list(cate))
  }
  tmp <- lapply(seriesData, boxplot.stats)
  #browser()
  grps[[grp]] <- lapply(tmp, function(x) x$stats)
}

e <- e_chart() 
for (grp in 1:3) {
  e$x$opts$series[[grp]] <- list(
    name = paste0('category',grp),
    type = 'boxplot',
    data = grps[[grp]]
    #tooltip = list(formatter=
    #  htmlwidgets::JS("function(param) { return ['Experiment ' + param.name + ': ',    'upper: ' + param.data[0], 'Q1: ' + param.data[1],          'median: ' + param.data[2],'Q3: ' + param.data[3], 'lower: ' + param.data[4] ].join('<br/>'); }"))
  )
}
e$x$opts$xAxis <- list(
  type = 'category',
  data = as.character(1:18),
  boundaryGap = TRUE,
  nameGap = 30,
  splitArea = list(show=TRUE),
  axisLabel = list(formatter = "exprmt {value}"),
  splitLine = list(show=FALSE)
)
e$x$opts$yAxis <- list(
  type = 'value',
  name = 'Value',
  min = -200,
  max = 400,
  splitArea = list(show=FALSE)  
)
e$x$opts$legend$data <- list('category1', 'category2', 'category3')
e$x$opts$tooltip <- list(trigger='item', axisPointer=list(type='shadow'))
e %>% e_datazoom(start = 50)

Note: There is a lingering problem with passing JS formatting code from echarts4r to Echarts.js. The tooltip formatter comes up as string instead of a JS function, so it was commented out.

munoztd0 commented 2 years ago

Wow, a good 5-star question 🏆 There may be a more elegant way of doing this, but here is my way.

Note: There is a lingering problem with passing JS formatting code from echarts4r to Echarts.js. The tooltip formatter comes up as string instead of a JS function, so it was commented out.

Created a gist function to do it -> https://gist.github.com/munoztd0/c860717d1f29e8a1b9114c46e945202e