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.
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>
chartjs
component from chart.js
library.onMount
function that is called on component initialization.onMount
function to initialize data for rendered chart object. canvas
tag. Free Resources