Skip to content

Instantly share code, notes, and snippets.

@helgasoft
Last active January 3, 2022 03:44
Show Gist options
  • Select an option

  • Save helgasoft/b74c4f5c0532c83a8c0bbf571ae8cd02 to your computer and use it in GitHub Desktop.

Select an option

Save helgasoft/b74c4f5c0532c83a8c0bbf571ae8cd02 to your computer and use it in GitHub Desktop.
R | ECharts | area bands (confidence bands)
#' Area band (confidence bands) is a 'custom' serie with lower and upper boundaries
#' When type='polygon', coordinates of the two boundaries are chained into a polygon and displayed as one.
#' When type='stack', two (smooth) stacked lines are drawn, one with customizable areaStyle.
#' The upper boundary coordinates should be values added on top of the lower boundary coordinates.
#' Standard and custom(formatter) tooltips could be used.
#'
#' ec.init(load='custom') will preset values like dataset, xAxis, etc.
#' those could be customized (like xAxis below), and new ones added - like legend and tooltip.
library(echarty)
set.seed(5)
df <- data.frame( x = 1:10, y = runif(10, 5, 10)) %>%
dplyr::mutate(lwr = y-runif(10, 1, 3), upr = y+runif(10, 2, 4))
# --------- type='stack'
p <- df %>% ec.init(load='custom')
p$x$opts$xAxis <- list(type='category', boundaryGap=FALSE)
p$x$opts$series <- append( list(list(type='line', color='gold', name='line1')),
ecr.band(df, 'lwr', 'upr', type='stack', name='stak') #, smooth=FALSE)
)
p$x$opts$tooltip <- list(trigger = 'axis'
,formatter = htmlwidgets::JS("function(x) {
let str = x.length>1
? 'high <b>'+x[2].value[2]+'</b><br>line <b>'+x[0].value[1]+'</b><br>low <b>'+x[1].value[1]+'</b>'
: 'line <b>'+x[0].value[1]+'</b>';
return str; }"))
p$x$opts$legend <- list(ii='')
p
# --------- type='polygon'
p <- df %>% ec.init(load='custom')
p$x$opts$xAxis <- list(type='category', boundaryGap=FALSE)
p$x$opts$series <- append( list(list(type='line', color='gold', name='line1')),
ecr.band(df, 'lwr', 'upr', type='polygon', name='poly')
)
p$x$opts$tooltip <- list(trigger = 'axis')
p$x$opts$legend <- list(ii='')
p
@keatonwilson

Copy link
Copy Markdown

Works great! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment