How to create charts with Svelte and Chart.js
Javascript provides a set of libraries containing pre-written codes used for easier development in Javascript applications. Chart.js is one of the many open-source libraries of Js that is used for better data visualization. It supports eight different types of charts such as line, bar, scatter, pie, area, polar, bubble, and radar.
Svelte or any other Javascript application can use the chart.js library to give a visual representation of the data. We can install chart.js in the project using the command below:
npm install chart.js
Once the chart.js library is installed in the project directory, all the methods of that library are accessible now. The methods from the library can be used in any Javascript application by importing them into the application file.
Code example
Let's look at the code below:
<script>
import chartjs from 'chart.js';
import { onMount } from 'svelte';
let chartData = [20, 100, 50, 12, 20, 130, 45];
let Labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];
let ctx;
let chartCanvas;
onMount(async (promise) => {
ctx = chartCanvas.getContext('2d');
var chart = new chartjs(ctx, {
type: 'bar',
data: {
labels: Labels,
datasets: [{
label: 'Unit Sales',
data: chartData
}]
}
});
});
</script>
<canvas bind:this={chartCanvas} id="myChart"></canvas>
Code explanation
- Line 1: We import
chartjscomponent fromchart.jslibrary. - Line 2: We import the
onMountfunction that is called on component initialization. - Line 10: We call the
onMountfunction to initialize data for rendered chart object. - Lines 12-18: We define the type, data, and labels for the chart.
- Line 25: We render the chart by binding the defined object with an HTML
canvastag.
Free Resources