Skip to content

Instantly share code, notes, and snippets.

@pozil
Created July 4, 2022 09:58
Show Gist options
  • Save pozil/fe2336e0fb47d796c87f1e5da7f4144a to your computer and use it in GitHub Desktop.
Save pozil/fe2336e0fb47d796c87f1e5da7f4144a to your computer and use it in GitHub Desktop.
Drawing a Sankey Chart with Lightning Web Components and Chartjs

Drawing a Sankey Chart with Chartjs

This Gist explains how to draw a Sankey chart on the Salesforce Platform with Lightning Web Components. We use the Chart.js library and the chartjs-chart-sankey plugin. For the sake of simplicy we start from an existing Salesforce project: LWC Recipes.

  1. Install LWC Recipes and make sure that you can see the Chart.js recipe located in the 3rd Party Libs tab.
  2. Enable Lightning Web Security or you'll get the following error message:

    TypeError: ResizeObserver is not a constructor

  3. Download the latest version of the chartjs-chart-sankey plugin from this CDN link and rename the file to chartJsSankey.js.
  4. Move chartJsSankey.js to force-app/main/default/staticresources/.
  5. Copy chartJs.resource-meta.xml as chartJsSankey.resource-meta.xml in the same folder.
  6. Replace the force-app/main/default/lwc/libsChartjs/libsChartjs.js file with the one provided in this Gist.
/* global Chart */
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import chartjs from '@salesforce/resourceUrl/chartJs';
import chartjsSankey from '@salesforce/resourceUrl/chartJsSankey';
const colors = {
a: 'red',
b: 'green',
c: 'blue',
d: 'gray'
};
const getColor = (key) => colors[key];
export default class LibsChartjs extends LightningElement {
error;
chart;
chartjsInitialized = false;
config = {
type: 'sankey',
data: {
datasets: [
{
label: 'My sankey',
data: [
{ from: 'a', to: 'b', flow: 10 },
{ from: 'a', to: 'c', flow: 5 },
{ from: 'b', to: 'c', flow: 10 },
{ from: 'd', to: 'c', flow: 7 }
],
colorFrom: (c) =>
getColor(c.dataset.data[c.dataIndex].from),
colorTo: (c) => getColor(c.dataset.data[c.dataIndex].to),
colorMode: 'gradient', // or 'from' or 'to'
/* optional labels */
labels: {
a: 'Label A',
b: 'Label B',
c: 'Label C',
d: 'Label D'
},
/* optional priority */
priority: {
b: 1,
d: 0
},
/* optional column overrides */
column: {
d: 1
},
size: 'max' // or 'min' if flow overlap is preferred
}
]
}
};
async renderedCallback() {
if (this.chartjsInitialized) {
return;
}
this.chartjsInitialized = true;
try {
await loadScript(this, chartjs);
await loadScript(this, chartjsSankey);
const canvas = document.createElement('canvas');
this.template.querySelector('div.chart').appendChild(canvas);
const ctx = canvas.getContext('2d');
this.chart = new Chart(ctx, this.config);
} catch (error) {
console.error(error);
this.error = error;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment