Skip to content

Chart adapter (draw with an external chart library) ​

Since 1.6.0

chartAdapter and createChart were added in 1.6.0.

MaxGrid ships no chart library. Instead it turns the grid data into a chart-friendly shape (categories and series) and hands it to an adapter that you write for the library you chose (Chart.js, Highcharts, ECharts, hand-drawn SVG...). Nothing changes unless you turn it on.

Try it in the gallery examples Selected cells as an SVG chart and Draw with Chart.js, Build a chart with Highcharts.

Write an adapter ​

ts
createGrid(el, {
  columns,
  rows,
  rowKey: 'id',
  cellSelection: 'multiple',
  chartAdapter: {
    create({ container, getData, type, options, locale, theme }) {
      // draw a chart inside container and return a handle for later updates
      return {
        update(data) {
          /* redraw with the new data */
        },
        destroy() {
          /* clean up the chart and listeners */
        },
        resize() {
          /* optional: when the size changed */
        },
      };
    },
  },
});

ChartContext

NameMeaning
containerThe element to draw into
getData()The current data { categories: string[], series: [{ id, name, values: (number | null)[] }] }
type'column' | 'bar' | 'line' | 'area' | 'pie'. The type select in the popup changes it (see the table below)
optionsThe options you passed to createChart, unchanged
locale, themeThe grid language and 'light' | 'dark' (from the container's data-theme or .dark, otherwise the system setting)

Create a chart ​

ts
const chart = api.createChart('#chart', {
  source: 'selection', // 'selection' | 'visible' | 'all' | { columns: ['region', 'q1'], rows?: [1, 2] }
  type: 'column',
  categoryColumn: 'region', // default: the first text or date column
  seriesColumns: ['q1', 'q2'], // default: every numeric column
  limit: 500, // row cap (default 500)
  live: true, // default true
});
chart?.refresh(); // push the current data right now
chart?.destroy();
  • Choosing data: selection uses the rows and columns of the selected cells (with no cell selection, the selected rows by the visible columns). Nothing selected throws invalid-option. visible is the rows left after filtering and sorting, all is every row (visible columns only). The object form names the column ids yourself.
  • Categories and series: categories (the horizontal axis) come from categoryColumn, otherwise the first text or date column among the chosen ones (the displayed text); with none, row numbers. Series come from seriesColumns, otherwise the numeric columns (kind number, or every value is a number). Non-numeric cells become null. With no numeric column at all it throws invalid-option.
  • live: while on, the data is pushed again when edits, added or removed rows, filters, sorting, selection or column visibility change. Several changes in one frame send once, and identical data is not sent. With live: false data is sent only when you call refresh().
  • Destroying the grid destroys its charts too. chart.destroy() is safe to call twice.
  • Without an adapter an error event (chart-adapter-missing) is emitted and createChart throws invalid-option. If the adapter throws, a callback-error event is emitted.
  • Events chartCreated and chartUpdated { type, categories, series }, and the cancelable hook beforeChartCreate({ type, source, data }) (on false, createChart returns null).

Types an adapter must draw ​

The popup and createChart({ type }) only pass type to the adapter; they do not draw anything. Telling the types apart is the adapter's job, and an adapter must draw all five. If one type is left out and drawn in the default shape, picking it in the popup leaves the chart unchanged, which looks like a bug.

typeWhat to draw
columnVertical bars, the series side by side in each category
barHorizontal bars: category names on the left, the value axis below
lineOne line per series
areaThe area under each line filled
pieA pie of the first series only, even when there are several

Chart.js and Highcharts draw bar horizontally by themselves (just map the name, as in the recipes below); only an adapter that draws by hand has to build bar itself. The small SVG adapter on this page draws vertical bars only, to stay short, so do not use it as is behind the popup; for a complete one, see the gallery example Create a chart from the right-click menu.

"Create chart" in the cell menu ​

With chartAdapter set and at least one numeric column in the selection (or in the right-clicked cell), the cell context menu gets Create chart. It opens a small window over the grid with a chart type select at the top (column, bar, line, area, pie). Changing it rebuilds the adapter with the new type. The close button or Esc closes the window.

Recipe: a small SVG adapter ​

ts
const svgAdapter = {
  create({ container, getData, type }) {
    const NS = 'http://www.w3.org/2000/svg';
    const svg = document.createElementNS(NS, 'svg');
    svg.setAttribute('viewBox', '0 0 400 200');
    svg.style.width = '100%';
    container.append(svg);
    const colors = ['#2563eb', '#16a34a', '#d97706', '#9333ea', '#dc2626'];
    const draw = (data) => {
      svg.replaceChildren();
      const max = Math.max(1, ...data.series.flatMap((s) => s.values.map((v) => v ?? 0)));
      const slot = 380 / Math.max(1, data.categories.length);
      data.series.forEach((s, si) => {
        s.values.forEach((value, i) => {
          if (value === null) return;
          const h = (value / max) * 170;
          const bar = document.createElementNS(NS, 'rect');
          const w = slot / (data.series.length + 1);
          bar.setAttribute('x', String(10 + i * slot + si * w));
          bar.setAttribute('y', String(180 - h));
          bar.setAttribute('width', String(w * 0.9));
          bar.setAttribute('height', String(h));
          bar.setAttribute('fill', colors[si % colors.length]);
          svg.append(bar);
        });
      });
    };
    draw(getData());
    return { update: draw, destroy: () => svg.remove() };
  },
};

Recipe: Chart.js adapter ​

ts
import Chart from 'chart.js/auto';

const chartJsAdapter = {
  create({ container, getData, type, options }) {
    const canvas = document.createElement('canvas');
    container.append(canvas);
    const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[type];
    const toConfig = (data) => ({
      labels: data.categories,
      datasets: data.series.map((s) => ({
        label: s.name,
        data: s.values,
        fill: type === 'area',
      })),
    });
    const chart = new Chart(canvas, {
      type: kind,
      data: toConfig(getData()),
      options: { indexAxis: type === 'bar' ? 'y' : 'x', maintainAspectRatio: false, ...options },
    });
    return {
      update(data) {
        chart.data = toConfig(data);
        chart.update();
      },
      destroy: () => chart.destroy(),
      resize: () => chart.resize(),
    };
  },
};

If your page uses script tags, load Chart from a CDN first and use the same adapter.

Recipe: Highcharts adapter ​

Highcharts plugs into the same place as the Chart.js adapter above. The recipe below is all the adapter code; MaxGrid does not provide Highcharts-specific support beyond it.

License

Highcharts is a separate commercial library. Commercial use needs its own Highcharts license, and MaxGrid does not include it. Check the license terms at Highcharts.

ts
import Highcharts from 'highcharts';

const HC_TYPE = { column: 'column', bar: 'bar', line: 'line', area: 'area', pie: 'pie' };

// Each series becomes one bar/line set; a pie uses the first series only. null values are drawn as gaps.
const seriesOf = (type, { categories, series }) =>
  type === 'pie'
    ? [
        {
          type: 'pie',
          name: series[0]?.name ?? '',
          data: categories.map((name, i) => ({ name, y: series[0]?.values[i] ?? null })),
        },
      ]
    : series.map((s) => ({ type: HC_TYPE[type], name: s.name, data: s.values }));

// Read the colors from the grid's CSS variables (--mxg-*).
function theme(el) {
  const css = getComputedStyle(el);
  const v = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
  const [bg, fg, line] = [
    v('--mxg-bg', '#fff'),
    v('--mxg-fg', '#1f2933'),
    v('--mxg-border', '#d9dee5'),
  ];
  const text = { style: { color: fg } };
  return {
    chart: { backgroundColor: bg },
    title: text,
    legend: { itemStyle: { color: fg } },
    xAxis: { labels: text, lineColor: line },
    yAxis: { labels: text, gridLineColor: line, title: text },
    tooltip: { backgroundColor: bg, style: { color: fg } },
  };
}

const highchartsAdapter = {
  create({ container, getData, type, options }) {
    const data = getData();
    const chart = Highcharts.chart(container, {
      chart: { type: HC_TYPE[type] },
      title: { text: options?.title ?? '' },
      xAxis: { categories: data.categories },
      yAxis: { title: { text: undefined } },
      series: seriesOf(type, data),
      accessibility: { enabled: false }, // set true when you load the accessibility module
      ...theme(container),
      ...options?.highcharts,
    });
    // Re-apply the colors when the theme changes.
    const watcher = new MutationObserver(() => chart.update(theme(container)));
    watcher.observe(document.documentElement, {
      attributes: true,
      subtree: true,
      attributeFilter: ['data-mxg-theme'],
    });
    return {
      update: (next) =>
        chart.update(
          { xAxis: { categories: next.categories }, series: seriesOf(type, next) },
          true,
          true,
        ),
      destroy: () => {
        watcher.disconnect();
        chart.destroy();
      },
      resize: () => chart.reflow(),
    };
  },
};

On a script-tag page, load it from the official CDN with a pinned version. When this guide was written, the newest stable version was 13.1.1.

html
<script
  src="https://code.highcharts.com/13.1.1/highcharts.js"
  integrity="sha384-FXT8Mj1JsVEsCNEB3qjrU1JPYJ94Ku7uMe0eopjumL2jEkPl1O9YeAZJn+qsOFVW"
  crossorigin="anonymous"
></script>
  • With integrity (SRI) the browser refuses the file if it ever changes. When you bump the version, recompute the hash from the new file (openssl dgst -sha384 -binary highcharts.js | openssl base64 -A).
  • With a Content Security Policy, allow https://code.highcharts.com in script-src. This CDN rejects requests without a Referer header, so on pages with Referrer-Policy: no-referrer host the file yourself.
  • The recipe leaves accessibility.enabled: false because it does not load the Highcharts accessibility module, and it describes the chart with role="img" and a label on the container instead (see the gallery example). If you load the module, pass { accessibility: { enabled: true } } through options.highcharts.
  • The gallery examples Build a chart with Highcharts and Switch Highcharts chart types load Highcharts only when you press the button.

Example: ECharts adapter ​

ECharts plugs into the same place as the Chart.js adapter above. The recipe below is all the adapter code; MaxGrid does not provide ECharts-specific support beyond it.

License

ECharts is a separate open-source library from the Apache Software Foundation, released under the Apache License 2.0. MaxGrid does not include it. Keep its license and notice file when you redistribute it.

ts
const EC_TYPE = { column: 'bar', bar: 'bar', line: 'line', area: 'line' };

// Each series becomes one bar/line set; a pie uses the first series only. null values are drawn as gaps.
const seriesOf = (type, { categories, series }) =>
  type === 'pie'
    ? [
        {
          type: 'pie',
          name: series[0]?.name ?? '',
          data: categories.map((name, i) => ({ name, value: series[0]?.values[i] ?? null })),
        },
      ]
    : series.map((s) => ({
        type: EC_TYPE[type],
        name: s.name,
        data: s.values,
        ...(type === 'area' ? { areaStyle: {} } : {}),
      }));

// A horizontal bar chart swaps the axes; a pie has none.
const axesOf = (type, { categories }) => {
  if (type === 'pie') return {};
  const [cat, val] = [{ type: 'category', data: categories }, { type: 'value' }];
  return type === 'bar' ? { xAxis: val, yAxis: cat } : { xAxis: cat, yAxis: val };
};

// Read the colors from the grid's CSS variables (--mxg-*).
function theme(el, type) {
  const css = getComputedStyle(el);
  const v = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
  const [bg, fg, line] = [
    v('--mxg-bg', '#fff'),
    v('--mxg-fg', '#1f2933'),
    v('--mxg-border', '#d9dee5'),
  ];
  const axis = {
    axisLabel: { color: fg },
    axisLine: { lineStyle: { color: line } },
    splitLine: { lineStyle: { color: line } },
  };
  return {
    backgroundColor: bg,
    textStyle: { color: fg },
    title: { textStyle: { color: fg } },
    legend: { textStyle: { color: fg } },
    tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
    ...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
  };
}

const echartsAdapter = {
  create({ container, getData, type, options }) {
    const chart = echarts.init(container, null, { renderer: 'svg' });
    chart.setOption({
      title: { text: options?.title ?? '' },
      tooltip: { trigger: type === 'pie' ? 'item' : 'axis' },
      legend: {},
      series: seriesOf(type, getData()),
      ...axesOf(type, getData()),
      ...theme(container, type),
      ...options?.echarts,
    });
    // Re-apply the colors when the theme changes.
    const watcher = new MutationObserver(() => chart.setOption(theme(container, type)));
    watcher.observe(document.documentElement, {
      attributes: true,
      subtree: true,
      attributeFilter: ['data-mxg-theme'],
    });
    return {
      update: (next) =>
        chart.setOption(
          { ...axesOf(type, next), series: seriesOf(type, next) },
          { replaceMerge: ['series'] },
        ),
      destroy: () => {
        watcher.disconnect();
        chart.dispose();
      },
      resize: () => chart.resize(),
    };
  },
};

On a script-tag page, load it from the jsDelivr CDN with a pinned version. When this guide was written, the newest stable version was 6.1.0.

html
<script
  src="https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js"
  integrity="sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD"
  crossorigin="anonymous"
></script>
  • With integrity (SRI) the browser refuses the file if it ever changes. When you bump the version, recompute the hash from the new file (openssl dgst -sha384 -binary echarts.min.js | openssl base64 -A).
  • With a Content Security Policy, allow https://cdn.jsdelivr.net in script-src.
  • The recipe uses the SVG renderer, which draws crisp text in the grid theme colors, and describes the chart with role="img" and a label on the container (see the gallery example). ECharts has its own aria option; pass { aria: { enabled: true } } through options.echarts to use it as well.
  • The gallery examples Build a chart with ECharts and Switch ECharts chart types load ECharts only when you press the button.