Visuals are your best option for presenting data in the modern world. In reality, no one has the time to read through a large amount of information. You must be able to use data to tell your story in a way that is simple and quick for everyone to comprehend.
Data visualization, otherwise known as data viz., refers to the process of presenting data in a visual or graphical format. With data visualization tools, you can quickly present data and make it easier to digest.
As with every technical decision, choosing your tools is important based on their ease of integration, the number of features they provide, and their intuitiveness.
Throughout this article, we'll go over ten of the most commonly used Javascript data visualizations, some of which I've encountered the most frequently as a software engineer, as well as some I believe deserve more attention. We'll look at various libraries that offer data visualization techniques, such as the basic level chart (bar charts, pie charts, and so on), financial charts (candlesticks, trading indicators), map charts, scatter plot charts, and many more. We’ll also cover their capabilities and drawbacks, along with instructions and code samples on how to use them.
ApexChart
ApexChart is an open-source charting library that helps you create beautiful and interactive charts with limited code. ApexChart supports 16 chart types, including line, bar, area, pie chart, candlestick, heatmap, and many more.
In addition to providing beautiful charts, some of ApexChart's added advantages are that its charts are responsive and interactive—they are automatically rendered with customized icons that let you control the zoom of your charts, pan through datasets, and even let you export rendered charts as a PNG, SVG or CSV file. You can also create dynamic charts that allow you to load data on selections. They offer over 10+ different theme palettes for styling charts as well.
However, the Apexchart library is quite large, with its current version (v3.35.4) weighing in at around 496kb. As a result, when working with a large data set, you will begin to notice significant performance issues.
How to use
You can include ApexChart CDN in your project markup with:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
Optionally, you can also install the library via npm with the command below:
$ npm install apexcharts
Once installed, you can get started with rendering charts by creating an option object specifying your chart style and dataset. Below is an example of an area chart with a random dataset:
<head>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
</head>
<body>
<div id="chart"></div>
<script>
var options = {
chart: {
height: 280,
type: "area",
},
dataLabels: {
enabled: false,
},
series: [
{
name: "Series 1",
data: [75, 82, 68, 75],
},
],
fill: {
type: "gradient",
gradient: {
shadeIntensity: 1,
opacityFrom: 0.7,
opacityTo: 0.9,
stops: [0, 90, 100],
},
},
xaxis: {
categories: ["01 Jan", "02 Jan", "03 Jan", "04 Jan"],
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
</script>
</body>
Performance-wise, you can also explore this example with 1000 random datasets to see ApexChart performance with a large dataset.
To learn more: ApexChart Documentation
Chart.js
Chart.js is one of the most used JavaScript data visualization libraries and the second most starred on GitHub after D3.js, with over 57k stars as at the time of writing this article.
Chart.js provides simple, clean, and engaging charts that you can quickly incorporate into your application.
Some of its advantages are that it’s fairly easy to integrate this library into your application. It provides out-of-the-box support for nine different chart types, including Scatter Plot, Line, Bar, Pie, Donut, Bubble, Area, Radar, and Mixed Chart, all of which are also responsive and accessible by default. Additionally, its integration includes customizable labels, legends, hover pop-ups, and series toggling.
One of Chart.js' drawbacks is that its charts are rendered with a dull gray color by default, which can make styling different chart parts with different colors difficult when working with large datasets. You'll also need to put in extra effort to support basic chart features like zooming and panning.
How to use
Chart.js can be installed with npm via
$ npm install chart.js
Or include its script CDN link in your markup like below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
Chart.js usage is pretty much similar to that of ApexChart. To create a chart, you need to create a new instance of the Chart
object while adding the chart target, its dataset, and additional option as its parameters. Below is an example of a simple Pie Chart created with chart.js:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
</head>
<body>
<div class="container">
<div id="chart">
<canvas id="myChart" style="height: 60vh"></canvas>
</div>
</div>
</body>
<script>
const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Red", "Blue", "Green"],
datasets: [
{
label: "# Ratings",
data: [8, 19, 12],
backgroundColor: ["#f44336", "#3f51b5", "#009688"],
borderWidth: 2,
},
],
},
options: {
scales: {
y: {
beginAtZero: true,
},
},
responsive: false,
},
});
</script>
To learn more: Chart.js documentation
D3.js
D3.js is a javascript data viz library for adding dynamic and interactive visualizations to web applications. It is one of the most used and currently the most starred javascript data viz library on GitHub (with over 102k stars currently). Its first version was released in 2011, which is partly why it is so ubiquitous
D3.js differs from some of the other libraries mentioned in this tutorial. It does not directly provide charting features, such as how ApexCharts and Chart.js allow you to render charts by calling a single function. D3.js is more of a building block for constructing data visualization, i.e., it provides methods that let you gradually build your chart from ground up.
For this reason, it’s much more difficult to quickly create a simple chart with D3.js, as you need to know how its functions and modules work. As we'll see below, it also takes some pretty long code to create a basic chart with the library itself. However, its integration with other JavaScript libraries like react and vue has made it fairly easier to use.
How to use
You can get started with using D3.js by including its CDN link (which export a global d3
object) in your markup:
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
You can also install d3 in a node.js project with the command npm install d3
. Or using ES6 import:
<script type="module">
import * as d3 from "https://cdn.skypack.dev/d3@7";
</script>
Let's explore the following example of creating a simple line chart with d3.js
:
<script src="https://d3js.org/d3.v4.js"></script>
<div id="my_dataviz"></div>
<script>
var margin = { top: 10, right: 30, bottom: 30, left: 60 },
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var svg = d3
.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv(
"https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered_comma.csv",
function (d) {
return { date: d3.timeParse("%Y-%m-%d")(d.date), value: d.value };
},
function (data) {
var x = d3
.scaleTime()
.domain(
d3.extent(data, function (d) {
return d.date;
})
)
.range([0, width]);
svg
.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var y = d3
.scaleLinear()
.domain([
0,
d3.max(data, function (d) {
return +d.value;
}),
])
.range([height, 0]);
svg.append("g").call(d3.axisLeft(y));
svg
.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr(
"d",
d3
.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.value);
})
);
}
);
</script>
With the code above, you can see how we had to first create an SVG element, load our chart data set from a remote API, and also use d3 to append this data into different paths in our SVG element.
It’s also worth mentioning that there’s a D3.js graph gallery which is a collection of ready-made charts created with d3 like the example.
To learn more: D3.js documentation
Techan.js
Techan.js is a charting library built on top of D3.js for adding interactive financial charts to your application. Techan lets you add stock charts, including candlestick, OHCL, indicators, and further technical analysis, which is particularly useful for financial applications.
While this library is still admirably serving its purpose and actively being used, it has not been updated for over 6 years now. This might be a concern if you’d prefer a library that is being actively reviewed. Another drawback of Techan.js is that you’ll need background knowledge of how d3.js works before you can understand how the library itself works.
How to use
Before you can get started with using Techan.js in your web application, you’ll need to include it’s script CDN, along with d3.js CDN:
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="http://techanjs.org/techan.min.js"></script>
Explore the following example of creating a simple candlestick chart with techan and d3.js:
<style>
path.candle {
stroke: #000000;
}
path.candle.body {
stroke-width: 0;
}
path.candle.up {
fill: #00aa00;
stroke: #00aa00;
}
path.candle.down {
fill: #ff0000;
stroke: #ff0000;
}
</style>
<body>
<button>Update</button>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="http://techanjs.org/techan.min.js"></script>
<script>
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.timeParse("%d-%b-%y");
var x = techan.scale.financetime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var candlestick = techan.plot.candlestick().xScale(x).yScale(y);
var xAxis = d3.axisBottom().scale(x);
var yAxis = d3.axisLeft().scale(y);
var svg = d3
.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", function (error, data) {
var accessor = candlestick.accessor();
data = data
.slice(0, 200)
.map(function (d) {
return {
date: parseDate(d.Date),
open: +d.Open,
high: +d.High,
low: +d.Low,
close: +d.Close,
volume: +d.Volume,
};
})
.sort(function (a, b) {
return d3.ascending(accessor.d(a), accessor.d(b));
});
svg.append("g").attr("class", "candlestick");
svg
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")");
svg
.append("g")
.attr("class", "y axis")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
// Data to display initially
draw(data.slice(0, data.length - 20));
// Only want this button to be active if the data has loaded
d3.select("button")
.on("click", function () {
draw(data);
})
.style("display", "inline");
});
function draw(data) {
x.domain(data.map(candlestick.accessor().d));
y.domain(techan.scale.plot.ohlc(data, candlestick.accessor()).domain());
svg.selectAll("g.candlestick").datum(data).call(candlestick);
svg.selectAll("g.x.axis").call(xAxis);
svg.selectAll("g.y.axis").call(yAxis);
}
</script>
</body>
This example was recreated from techan.js gallery, which also includes code examples for the different types of financial charts the library supports.
To learn more: Techan.js documentation
AnyChart
AnyChart is another interesting charting library offering a different suite of chart types, including the basics charts (bar, pie, and others), different stock charts, and even PERT charts.
With AnyChart you can also integrate drawing tools into its stock charts, which is very useful in financial applications. AnyChart also offers chart localizations, with support for over 194 predefined locales, so you can visualize data for your users in different languages.
However, while AnyChart is open-source and free for non-profit use, you’ll need to purchase a license for use in commercial applications.
How to use
AnyChart offers integration with different languages, libraries, and frameworks; however, for this tutorial, we’ll be exploring its react plugin.
We can add AnyChart to our react application by installing with the following command:
$ npm install anychart-react
Once installed, we can then import its component and render a simple bar chart like below:
import AnyChart from "anychart-react/dist/anychart-react";
function App() {
return (
<div>
<h1>Hello</h1>
<AnyChart type="bar" data={[3, 6, 2, 7, 9]} title="Simple bar chart" />
</div>
);
}
export default App;
For integration with other languages and frameworks, you can refer to their documentation page here.
Taucharts
This is another interesting open-source chart library built on top of d3.js and mostly used for data exploration and analysis. However, its integration is independent of prior familiarity with d3.js, unlike Techan.js.
Taucharts has a nice framework and has lots of extensibility options. Its plugin infrastructure is adaptable, allowing you to write plugins quickly.
How to use
For a traditional HTML project, you’ll need to include d3.js, taurichart.js, along with the Tauri CSS file like below:
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/taucharts@2/dist/taucharts.min.css"
/>
<!-- .. -->
<script src="https://cdn.jsdelivr.net/d3js/latest/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/taucharts@2/dist/taucharts.min.js"></script>
</head>
You can also install with npm via:
$ npm install taucharts
And once the installation is completed, you can get started with integrating it in your application by creating a new instance of the Taucharts
object, including your dataset/data source, chart type, and other additional options to style your chart as its parameters.
Here’s what creating a simple line chart looks like with Taucharts:
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/taucharts@2/dist/taucharts.min.css"
/>
<!-- .. -->
<script src="https://cdn.jsdelivr.net/d3js/latest/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/taucharts@2/dist/taucharts.min.js"></script>
</head>
<body>
<div id="line"></div>
<script>
var datasource = [
{
type: "us",
count: 0,
date: "12-2013",
},
{
type: "us",
count: 10,
date: "01-2014",
},
{
type: "us",
count: 15,
date: "02-2014",
},
{
type: "us",
count: 12,
date: "03-2014",
},
{
type: "us",
count: 16,
date: "04-2014",
},
{
type: "us",
count: 13,
date: "05-2014",
},
{
type: "bug",
count: 21,
date: "01-2014",
},
{
type: "bug",
count: 19,
date: "02-2014",
},
{
type: "bug",
count: 23,
date: "03-2014",
},
{
type: "bug",
count: 26,
date: "04-2014",
},
{
type: "bug",
count: 23,
date: "05-2014",
},
];
var chart = new Taucharts.Chart({
data: datasource,
type: "line",
x: "date",
y: "count",
color: "type",
});
chart.renderTo(document.getElementById("line"));
</script>
</body>
</html>
To learn more: Taucharts documentation
Zoomcharts
Zoomcharts helps you add interactive data visualizations to your application with minimal input and development time by using its ready-to-go charts library. Zoomcharts supports different chart types, notably network charts, matrix charts, facet charts, time charts, geo-map charts, and many more.
Zoomcharts is free for non-production use, however, you’ll also need to purchase a license and obtain an API key once your application is in production. Otherwise the library will start showing an error in your browser console.
How to use
You can add zoomcharts to your web project with its CDN link:
<script src="https://cdn.zoomcharts-cloud.com/1/stable/zoomcharts.js"></script>
And depending on the type of chart you’re trying to render, it's pretty much easy to do with a few lines of code. Below is an example of a time chart from the zoomcharts documentation:
var t = new TimeChart({
container: document.getElementById("demo"),
data:
{
units:["h"],
url: "https://zoomcharts.com/dvsl/data/time-chart/temperature-kuldiga-h.json"
}
});
To learn more: Zoomcharts documentation
Canvasjs
Canvasjs offers a lightweight library for creating performant and elegant looking charts, with over 30 different customizable charts to choose from. Canvasjs stock chart, in comparison to some of the other stock chart libraries (Techan.js), tends to be more intuitive and interactive. It also offers integration with the top javascript frameworks including react, vue, and angular, as well as with java, spring, and PHP.
Additionally, like AnyChart, Canvasjs also offers localization of charts, so that you’re able to render your chart elements in different languages.
However, while Canvasjs is free for development use, the development version will add a watermark to all your charts, and you’ll need to obtain a license to use it in production.
How to use
To get started, you first need to download the canvasjs compressed library here. The downloaded file once uncompressed includes a canvasjs.min.js
file, which you can link to your website. Optionally, you could include the CDN directly in your markup like below:
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
And it's pretty much easy to start creating any chart. Here’s an example of a bubble chart from the Canvasjs documentation:
<html>
<head>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Comparison among Countries on Fertility Rate Vs Life Expectancy in 2009",
},
axisX: {
title: "Life Expectancy",
maximum: 85,
},
axisY: {
title: "Fertility Rate",
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "left",
},
data: [
{
type: "bubble",
legendText: "Size of Bubble Represents Population",
showInLegend: true,
legendMarkerType: "circle",
toolTipContent:
"<strong>{name}</strong> <br/> Fertility Rate: {y}<br/> Life Expectancy: {x} yrs<br/> Population: {z} mn",
dataPoints: [
{ x: 78.1, y: 2.0, z: 306.77, name: "US" },
{ x: 68.5, y: 2.15, z: 237.414, name: "Indonesia" },
{ x: 72.5, y: 1.86, z: 193.24, name: "Brazil" },
{ x: 76.5, y: 2.36, z: 112.24, name: "Mexico" },
{ x: 50.9, y: 5.56, z: 154.48, name: "Nigeria" },
{ x: 68.6, y: 1.54, z: 141.91, name: "Russia" },
{ x: 82.9, y: 1.37, z: 127.55, name: "Japan" },
{ x: 79.8, y: 1.36, z: 81.9, name: "Australia" },
{ x: 72.7, y: 2.78, z: 79.71, name: "Egypt" },
{ x: 80.1, y: 1.94, z: 61.81, name: "UK" },
{ x: 55.8, y: 4.76, z: 39.24, name: "Kenya" },
{ x: 81.5, y: 1.93, z: 21.95, name: "Australia" },
{ x: 68.1, y: 4.77, z: 31.09, name: "Iraq" },
{ x: 47.9, y: 6.42, z: 33.42, name: "Afghanistan" },
{ x: 50.3, y: 5.58, z: 18.55, name: "Angola" },
],
},
],
});
chart.render();
};
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%"></div>
</body>
</html>
For more information, and integrating with other javascript frameworks, refer to their official documentation.
Highcharts
Highcharts is another great data visualization solution offering interactive charting capability. Compared to the other libraries in this article, Highcharts charts seem to offer more ready-made chart types.
Highcharts charts offer a lot of unique features, you can integrate your chart with different theme options, you can even create 3D charts, export charts in different formats, and convert your rendered charts to data tables on the fly. Another awesome feature is that you can create charts that are accessible to screen readers by adding descriptions to chart elements.
However, while highcharts is also free for non-commercial and personal use, you’ll need to purchase a license to integrate its libraries into commercial applications.
How to use
It's easy to get started with using highchart by adding its script CDN to your application:
<script src="https://code.highcharts.com/highcharts.js"></script>
And depending on the additional plugin you want to use, you’ll also need to import them independently.
It also requires less code to create high-level charts with this library. With this map projection example from their documentation, we can see how easy it is to visualize the world population density on a map.
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<div id="container"></div>
<script>
(async () => {
const mapData = await fetch(
"https://code.highcharts.com/mapdata/custom/world.topo.json"
).then((response) => response.json());
const data = await fetch(
"https://cdn.jsdelivr.net/gh/highcharts/highcharts@v7.0.0/samples/data/world-population-density.json"
).then((response) => response.json());
// Initialize the chart
Highcharts.mapChart("container", {
title: {
text: "Predefined zoomed area",
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: "bottom",
},
},
mapView: {
projection: {
name: "WebMercator",
},
center: [10, 58],
zoom: 2.8,
},
colorAxis: {
min: 1,
max: 1000,
type: "logarithmic",
},
legend: {
title: {
text: "Population density per km²",
},
},
series: [
{
data,
mapData,
joinBy: ["iso-a2", "code"],
name: "Population density",
states: {
hover: {
color: "#a4edba",
},
},
tooltip: {
valueSuffix: "/km²",
},
},
],
});
})();
</script>
To learn more: Highcharts documentation
Toast UI Chart
Toast UI chart is another open-source chart solution. Toast UI isn’t a complete charting library per se; it’s more of a JavaScript library providing UI components similar to bootstrap. However, it has been included in this article since this type of thing is uncommon - UI libraries with support for charts.
Some of Toasts UI chart’s best features are that it’s lightweight, offers a wide range of chart types, and easily integrates charts via JavaScript components.
How to use
You can install Toast UI charts in your project with
$ npm install --save @toast-ui/chart
Or load its CDN via:
<link rel="stylesheet" href="https://uicdn.toast.com/chart/latest/toastui-chart.min.css" />
<script src="https://uicdn.toast.com/chart/latest/toastui-chart.min.js"></script>
Here's an interactive example of a live updating chart created with Toast UI chart:
<link
rel="stylesheet"
href="https://uicdn.toast.com/chart/latest/toastui-chart.min.css"
/>
<script src="https://uicdn.toast.com/chart/latest/toastui-chart.min.js"></script>
<div id="chart-area"></div>
<script>
const el = document.getElementById("chart-area");
const data = {
categories: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
series: [
{
name: "A",
data: [10, 100, 50, 40, 70, 55, 33, 70, 90, 110],
},
{
name: "B",
data: [60, 40, 10, 33, 70, 90, 100, 17, 40, 80],
},
],
};
const options = {
chart: { title: "LiveUpdate", width: 900, height: 400 },
xAxis: { pointOnColumn: false, title: { text: "X Title" } },
yAxis: { title: "Y Title" },
series: { shift: true },
};
const chart = toastui.Chart.areaChart({ el, data, options });
let index = 11;
const intervalId = setInterval(() => {
const random = Math.round(Math.random() * 100);
const random2 = Math.round(Math.random() * 100);
chart.addData([random, random2], index.toString());
index += 1;
if (index === 30) {
clearInterval(intervalId);
}
}, 1500);
</script>
To learn more: Toast UI documentation
Conclusion
And it’s a wrap! Throughout this article, we’ve explored ten different JavaScript data visualization libraries, the type of visualization tools they provide, additional features, their drawbacks, and how to get started with using them with interactive code samples.
We can’t definitively say which library is the best–that depends on how easily it integrates with your particular application and your intended use case–but hopefully, by now, you have some ideas on where to start.
This post was written by Elijah Asaolu, and I’m a software engineer and technical writer, actively sharing all I've learned through writing. You can also follow me on Twitter if you appreciate programming memes and tips.
Top comments (0)