Averages Past the Whole in JavaScript

Using ApexCharts with JavaScript

This Averages Past the Whole example uses ApexCharts.js directly in JavaScript, with no wrapper component.

Install it with npm install apexcharts, then mount the chart with new ApexCharts(element, options).render().

JavaScript installation guide
// Shared by the vanilla-js, React and Vue builds.

function money(v) {
  return (v < 0 ? '-$' : '$') + Math.abs(Math.round(v))
}
//
// Average profit per order by store, across all products (the wholes), and the
// same average over one product line (the parts). An average over a subset
// can be larger than the overall one, or fall on the other side of zero, so
// the parts here do both.
var STORES = ['Seattle', 'Denver', 'Austin', 'Chicago', 'Boston', 'Miami']
var ALL = [42, -18, 31, 24, 12, -9]
var LINES = {
  premium: [
    { x: 'Seattle', y: 42, highlight: 61 },
    { x: 'Denver', y: -18, highlight: -4 },
    { x: 'Austin', y: 31, highlight: 48 },
    { x: 'Chicago', y: 24, highlight: 19 },
    { x: 'Boston', y: 12, highlight: 27 },
    { x: 'Miami', y: -9, highlight: 6 },
  ],
  budget: [
    { x: 'Seattle', y: 42, highlight: 18 },
    { x: 'Denver', y: -18, highlight: -26 },
    { x: 'Austin', y: 31, highlight: 12 },
    { x: 'Chicago', y: 24, highlight: 28 },
    { x: 'Boston', y: 12, highlight: -3 },
    { x: 'Miami', y: -9, highlight: -21 },
  ],
}

function seriesFor(line) {
  return [
    {
      name: 'Avg profit per order',
      data: line
        ? LINES[line]
        : STORES.map(function (s, i) {
            return { x: s, y: ALL[i] }
          }),
    },
  ]
}

function pickLine(chart, line) {
  document.querySelectorAll('[data-line]').forEach(function (b) {
    b.classList.toggle('active', b.getAttribute('data-line') === line)
  })
  return chart.updateSeries(seriesFor(line))
}

function wireLines(chart) {
  document.querySelectorAll('[data-line]').forEach(function (b) {
    b.addEventListener('click', function () {
      pickLine(chart, b.getAttribute('data-line'))
    })
  })
}

var options = {
  series: seriesFor('premium'),
  chart: {
    id: 'profit',
    type: 'bar',
    height: 360,
    toolbar: { show: false },
  },
  colors: ['#0d9488'],
  plotOptions: {
    bar: { horizontal: true, barHeight: '62%', borderRadius: 4 },
  },
  dataLabels: {
    enabled: true,
    formatter: money,
  },
  xaxis: {
    labels: { formatter: money },
  },
  grid: { xaxis: { lines: { show: true } }, yaxis: { lines: { show: false } } },
  tooltip: {
    y: { formatter: money },
  },
}

var chart = new ApexCharts(document.querySelector('#chart'), options)
chart.render()

wireLines(chart)