Grouped, stacked and timelined

Here is a good example of the data-driven nature of ECharts.
With chart data well built, the actual chart display is trivial. It is like having a painting already drawn and framed, all that’s needed is a nail and hammer to put it on the wall. One may think of echarty as the nail - a final step before display.
A few noticeable details

  • columns could be rearranged to match the two axes, first column is X, second is Y
  • initializing ec.init() with grouped data presets the dataset and legend. Here dataset is not used, but legend is. Otherwise we would have just p<-ec.init()
  • nested grouping with lapply is easy!
  • option series data is converted from data.frame to a list with ec.data()
  • with timeline and options present, there is no need to set single chart series


library(echarty);  library(dplyr)

vv = iris |> mutate(Year= rep(2020:2022, 50)) |> 
    tidyr::pivot_longer(cols= Sepal.Length:Petal.Width) |> 
    group_by(Year, Species, name) |> 
    summarise(value= sum(value))
# rearrange columns for axes: X = Species (1st), Y = value (2nd)
vv <- vv |> relocate(Species, value) |> mutate(Species= as.character(Species))
options <-  lapply(vv |> group_by(Year) |> group_split(), function(y) {
    series <- lapply(y |> group_by(name) |> group_split(), function(s) {
       list(type = 'bar', stack = 'grp', data = ec.data(s,'values'))
  })
  list(title= list(text= unique(y$Year), top= 30), series= series)
})

vv |> group_by(name) |> ec.init(
    timeline= list(data= unique(vv$Year), axisType= 'category'),
    options= options
)