Skip to content

Instantly share code, notes, and snippets.

@ndemengel
Created January 16, 2023 14:09
Show Gist options
  • Save ndemengel/c619e504e16f3d59b5c59c09f744411f to your computer and use it in GitHub Desktop.
Save ndemengel/c619e504e16f3d59b5c59c09f744411f to your computer and use it in GitHub Desktop.
Example of building a line chart using Chart.js
function buildSimpleLineChart({data, containerEl, title, xField, yField, xTitle, yTitle}) {
const xs = data.map(d => d[xField]);
const ys = data.map(d => d[yField]);
const canvas = document.createElement('canvas');
canvas.style = 'width: 600px; height: 400px';
containerEl.appendChild(canvas);
return new Chart(canvas, {
data: {
datasets: [{
type: 'line',
data: ys,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 1)',
}],
labels: xs
},
options: {
responsive: false,
interaction: {
mode: 'index',
intersect: false,
},
stacked: false,
plugins: {
title: {
display: true,
text: title
},
legend: {
display: false,
}
},
scales: {
x: {
title: {
display: true,
text: xTitle
}
},
y: {
title: {
display: true,
text: yTitle
},
beginAtZero: true,
},
}
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment