Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to create charts with Svelte and Chart.js

Yasir Latif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
Command to install chartjs in project

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 chartjs component from chart.js library.
  • Line 2: We import the onMount function that is called on component initialization.
  • Line 10: We call the onMount function 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 canvas tag.

RELATED TAGS

javascript

CONTRIBUTOR

Yasir Latif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring