Explode to Observations in Angular

Using ApexCharts with Angular

This Explode to Observations example wires ApexCharts into Angular through the ng-apexcharts component.

Install it with npm install ng-apexcharts apexcharts, then mount the chart with <apx-chart [series]="series" [chart]="chart"></apx-chart>.

Angular charts guide

This demo uses imperative chart updates. The generated code is a faithful Angular translation: open it in CodeSandbox to run and tweak.

import { Component, AfterViewInit, OnDestroy, ViewChild } from '@angular/core';
import {
  ChartComponent,
  ApexAxisChartSeries,
  ApexNonAxisChartSeries,
  ApexChart,
  ApexXAxis,
  ApexYAxis,
  ApexTitleSubtitle,
  ApexDataLabels,
  ApexStroke,
  ApexFill,
  ApexLegend,
  ApexTooltip,
  ApexMarkers,
  ApexPlotOptions,
  ApexResponsive,
  ApexGrid,
  ApexAnnotations,
  ApexStates,
  ApexTheme,
  NgApexchartsModule,
} from 'ng-apexcharts';

import 'apexcharts/unit';

export type ChartOptions = {
  series?: ApexAxisChartSeries | ApexNonAxisChartSeries;
  chart?: ApexChart;
  xaxis?: ApexXAxis;
  yaxis?: ApexYAxis | ApexYAxis[];
  title?: ApexTitleSubtitle;
  subtitle?: ApexTitleSubtitle;
  dataLabels?: ApexDataLabels;
  stroke?: ApexStroke;
  fill?: ApexFill;
  legend?: ApexLegend;
  tooltip?: ApexTooltip;
  markers?: ApexMarkers;
  plotOptions?: ApexPlotOptions;
  responsive?: ApexResponsive[];
  grid?: ApexGrid;
  annotations?: ApexAnnotations;
  states?: ApexStates;
  theme?: ApexTheme;
  colors?: string[];
  labels?: any;
};

@Component({
  selector: 'app-chart',
  standalone: true,
  imports: [NgApexchartsModule],
  templateUrl: './chart.component.html',
})
export class AppChart implements AfterViewInit, OnDestroy {
  @ViewChild('chart') chart!: ChartComponent;
  private DELIVERIES: any = (function () {
        var seed = 20260814
        function rand() {
          seed = (seed * 16807) % 2147483647
          return (seed - 1) / 2147483646
        }
        var out = []
        for (var i = 0; i < 640; i++) {
          var u1 = Math.max(rand(), 1e-9)
          var u2 = rand()
          var z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)
          // Log-normal: a delivery can run very late but never finish early.
          out.push(Math.round(Math.exp(3.15 + z * 0.42)))
        }
        return out
      })();

  private HISTOGRAM_SERIES: any = [{ name: 'Deliveries', data: this.DELIVERIES }];

  private RAMP: any = ['#4e8cff', '#59c2b0', '#e8c14a', '#ef7d3a', '#d94040'];

  private rampColor = (t: any): any => {
        var scaled = Math.max(0, Math.min(1, t)) * (this.RAMP.length - 1)
        var i = Math.min(this.RAMP.length - 2, Math.floor(scaled))
        var f = scaled - i
        var a = this.RAMP[i]
        var b = this.RAMP[i + 1]
        var mix = function (o) {
          var av = parseInt(a.substr(o, 2), 16)
          var bv = parseInt(b.substr(o, 2), 16)
          var v = Math.round(av + (bv - av) * f)
          return (v < 16 ? '0' : '') + v.toString(16)
        }
        return '#' + mix(1) + mix(3) + mix(5)
      };

  private setReadout = (text: any): any => {
        var el = document.querySelector('#readout')
        if (el) el.innerHTML = text
      };

  private setActive = (exploded: any): any => {
        var buttons = [].slice.call(document.querySelectorAll('[data-explode]'))
        buttons.forEach(function (b) {
          b.className =
            (b.getAttribute('data-explode') === 'true') === exploded ? 'on' : ''
        })
      };

  private wireExplode = (chart: any): any => {
        var buttons = [].slice.call(document.querySelectorAll('[data-explode]'))
  
        buttons.forEach(function (b) {
          b.addEventListener('click', function () {
            // The active view's button is a no-op: re-requesting the readings while
            // already exploded would ask rowSeries() of a unit chart, which has no
            // rows to hand back.
            if (b.className === 'on') return
            var explode = b.getAttribute('data-explode') === 'true'
            this.setActive(explode)
  
            if (explode) {
              // The whole point: nothing about the sample is passed in here. The
              // chart already knows which observations it counted into each bar, so
              // rowSeries() returns one cluster per bar holding exactly those rows.
              var rows = chart.rowSeries()
              var total = rows.reduce(function (n, c) {
                return n + c.data.length
              }, 0)
  
              // What comes back is ordinary series data, so it can be decorated.
              // Colouring each bar's dots by how late that bar was keeps the
              // distribution readable once the bars are gone: without this the blob
              // is 640 identical dots and you cannot tell a quick delivery from a
              // disastrous one.
              rows.forEach(function (cluster, k) {
                var color = this.rampColor(rows.length > 1 ? k / (rows.length - 1) : 0)
                cluster.data.forEach(function (d) {
                  d.fillColor = color
                })
              })
              chart.updateOptions({
                chart: { type: 'unit' },
                series: rows,
                plotOptions: {
                  unit: {
                    // NOT 'columns'. That layout would stack each bin's dots back
                    // into a column the same height and place as the bar they left,
                    // so the objects would travel a few pixels and the whole thing
                    // would look like a redraw. 'packed' gathers them into one blob,
                    // which is a real journey.
                    layout: 'packed',
                    unitValue: 1,
                    size: 3,
                  },
                },
                legend: { show: false },
              })
              this.setReadout(
                'One dot per delivery: <b>' +
                  total +
                  '</b> of them, ' +
                  'gathered out of <b>' +
                  rows.length +
                  '</b> bars.',
              )
            } else {
              chart.updateOptions({
                chart: { type: 'histogram' },
                series: this.HISTOGRAM_SERIES,
                legend: { show: false },
              })
              this.setReadout(
                'Every bar is a count of the deliveries that landed in its range.',
              )
            }
          })
        })
  
        this.setActive(false)
        this.setReadout('Every bar is a count of the deliveries that landed in its range.')
      };

  public chartOptions: Partial<ChartOptions> = {
          series: this.HISTOGRAM_SERIES,
          chart: {
            id: 'explodeHist',
            type: 'histogram',
            height: 420,
            toolbar: {
              show: false,
            },
            animations: {
              chartTypeMorph: {
                speed: 900,
              },
            },
          },
          plotOptions: {
            histogram: {
              bins: 22,
            },
          },
          colors: ['#4e8cff'],
          legend: {
            show: false,
          },
          xaxis: {
            title: {
              text: 'Delivery time (minutes)',
            },
            labels: {
              formatter: (val) => {
                return Math.round(val)
              },
            },
          },
          yaxis: {
            title: {
              text: 'Deliveries',
            },
          },
        };
  ngAfterViewInit() {
    (window as any).ApexCharts.setLicense('APEX-eyJleHBpcnlEYXRlIjoiMjEyNi0wNy0wNCIsImlzc3VlRGF0ZSI6IjIwMjYtMDctMjgiLCJwbGFuIjoicHJlbWl1bSIsImRvbWFpbnMiOlsiYXBleGNoYXJ0cy5jb20iLCIxMjcuMC4wLjEiLCJsb2NhbGhvc3QiXSwic2lnIjoieVBmb1VCc0Z3TU9ZdUEyaEZkR0I2Y1FtZ0JITUtXcVdJSjB2NVRESXRZbFR3eDJMUmh6R2x0RUc3VXJ4X0s3b25ZMWRZb2Z2VGItN01ydFYyNDVyOWcifQ==');
    this.wireExplode(this.chart)

    function wireExplode(chart) {
          var buttons = [].slice.call(document.querySelectorAll('[data-explode]'))

          buttons.forEach(function (b) {
            b.addEventListener('click', () => {
              // The active view's button is a no-op: re-requesting the readings while
              // already exploded would ask rowSeries() of a unit chart, which has no
              // rows to hand back.
              if (b.className === 'on') return
              var explode = b.getAttribute('data-explode') === 'true'
              this.setActive(explode)

              if (explode) {
                // The whole point: nothing about the sample is passed in here. The
                // chart already knows which observations it counted into each bar, so
                // rowSeries() returns one cluster per bar holding exactly those rows.
                var rows = this.chart.rowSeries()
                var total = rows.reduce(function (n, c) {
                  return n + c.data.length
                }, 0)

                // What comes back is ordinary series data, so it can be decorated.
                // Colouring each bar's dots by how late that bar was keeps the
                // distribution readable once the bars are gone: without this the blob
                // is 640 identical dots and you cannot tell a quick delivery from a
                // disastrous one.
                rows.forEach(function (cluster, k) {
                  var color = this.rampColor(rows.length > 1 ? k / (rows.length - 1) : 0)
                  cluster.data.forEach(function (d) {
                    d.fillColor = color
                  })
                })
                this.chart.updateOptions({
                  chart: { type: 'unit' },
                  series: rows,
                  plotOptions: {
                    unit: {
                      // NOT 'columns'. That layout would stack each bin's dots back
                      // into a column the same height and place as the bar they left,
                      // so the objects would travel a few pixels and the whole thing
                      // would look like a redraw. 'packed' gathers them into one blob,
                      // which is a real journey.
                      layout: 'packed',
                      unitValue: 1,
                      size: 3,
                    },
                  },
                  legend: { show: false },
                })
                this.setReadout(
                  'One dot per delivery: <b>' +
                    total +
                    '</b> of them, ' +
                    'gathered out of <b>' +
                    rows.length +
                    '</b> bars.',
                )
              } else {
                this.chart.updateOptions({
                  chart: { type: 'histogram' },
                  series: this.HISTOGRAM_SERIES,
                  legend: { show: false },
                })
                this.setReadout(
                  'Every bar is a count of the deliveries that landed in its range.',
                )
              }
            })
          })

          this.setActive(false)
          this.setReadout('Every bar is a count of the deliveries that landed in its range.')
        }
  }

  ngOnDestroy() {
    // no cleanup needed
  }
}