Let's assume that you have the following line graph:
javascriptvar graph = { type: 'line', data: { labels: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'], datasets: [{ label: 'users', borderColor: '#48ac98', borderWidth: 4, backgroundColor: 'rgba(72, 172, 152, 1)', borderRadius: 10, pointRadius: 0, data: ['24', '23', '26', '27', '23', '28', '22'] }] }, options: { responsive: true } } let canvas = document.getElementById('graph'); let ctx = canvas.getContext('2d'); let chart = new Chart(ctx, graph);
If you want to change from a line to a bar graph dynamically, you can use chart.update()
:
javascriptvar changeToBar = () => { graph.type = (graph.type === 'line') ? 'bar' : 'line'; chart.update(); }
Here is the HTML:
html<button onclick = 'changeToBar()'>Change graph</button> <canvas id = 'graph'>
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.