Skip to main content

5 top picks for JavaScript chart libraries

In business apps, we often have to display data in a chart. To make this task easier, there are many JavaScript charting libraries to make our lives easier as frontend developers. In this article, we’ll look at five JavaScript chart libraries we can use to make and display charts.

Chart.js

Chart.js is a chart library that is available as a client-side JavaScript package. There are also derivatives for other frontend frameworks, like React, Vue, and Angular. It displays the chart on an HTML canvas element.

To use it, we can include the Chart.js library via CDN. then we add a canvas element to display our chart.

Our HTML code would be the following:

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>
<canvas id="chart" width="400" height="400"></canvas>

Then, in our JavaScript code, we write:

const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['red', 'green', 'blue'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'red',
        'green',
        'blue'
      ],
      borderColor: [
        'red',
        'green',
        'blue'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

Let’s break down the example above. We get the canvas element that we just created and create a Chart instance with it. label is the label for the legend, and datasets has the data for each bar on the bar chart.

backgroundColor and borderColor, as their names imply, set the color for each bar and the border color for each bar, respectively. borderWidth is the width of each bar in pixels.

In options, we can set the options for our chart. We have yAxesto set some options for the y-axis, and we specified beginAtZeroto true so that the y-axis begins at 0.

To make our chart responsive, we can specify the responsiveoption in the options object and set that to true.

Chartist

Chartist is another library to let us create simple charts. It also lets us create responsive charts. To create the same chart as above with Chartist, we first add the following HTML:

<script src='https://cdn.jsdelivr.net/npm/chartist@0.11.4/dist/chartist.min.js'></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<div class="ct-chart ct-perfect-fourth"></div>

Then we have to change the bar color with CSS:

.ct-chart .ct-bar:nth-of-type(1) {
  stroke: red;
}

.ct-chart .ct-bar:nth-of-type(2) {
  stroke: green;
}

.ct-chart .ct-bar:nth-of-type(3) {
  stroke: blue;
}

This will set the color for three bars. Then, we write the following JavaScript code:

const data = {
  labels: ['red', 'green', 'blue'],
  series: [
    [12, 9, 3]
  ]
};

const options = {
  high: 10,
  low: 0,
};
new Chartist.Bar('.ct-chart', data);

The data object has the label names in the labels array, and the series array has the magnitudes of the bars that we want to display.

options has the range of values to display on the y-axis. The smallest value on the y-axis is 0, and the highest is 10.

C3.js

C3.js is another easy-to-use JavaScript library for creating charts. It uses the D3 graphics library, so to create a chart with it, we’ll need both D3 and the C3 library itself.

We first include D3 and C3 JavaScript and CSS files in our HTML code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.15/c3.min.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.15/c3.min.css" rel="stylesheet">

<div id="chart"></div>

By default, C3 displays the chart in a div with ID chart. If we want to display the chart in a different element, we can add the bindtoproperty to the object we pass into the c3.generate function.

To create the bar chart, we add the following JavaScript code:

const chart = c3.generate({
  bindto: '#chart',
  data: {
    columns: [
      ['red', 12],
      ['green', 9],
      ['blue', 3]
    ],
    type: 'bar',
    colors: {
      red: 'red',
      green: 'green',
      blue: 'blue'
    },
  },
  bar: {
    width: {
      ratio: 0.5
    }
  }
});

We use the c3.generate function to create the chart. It just takes one object with all the options that we want to change to render the chart:

  • columns has the column options. Each entry has the column name and value.
  • type has the type of chart we want to display.
  • colors has the colors of each bar. The key is the column name and the keys are the color names.
  • bar has the options for the bars. The width and ratio of the width of the bar.

Other kinds of charts have their own options as well.

MetricsGraphics.js

MetricsGraphics.js is another D3-based charting library that lets us create charts with ease. It only supports displaying time series data with line charts, scatter plots, histograms, and data tables.

We can use this by including the JavaScript and CSS as follows:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js'></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/metrics-graphics/2.15.6/metricsgraphics.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/metrics-graphics/2.15.6/metricsgraphics.min.css">

<div id="chart"></div>

jQuery is required to display tooltips. Then, we can display a chart by writing the following JavaScript code:

MG.data_graphic({
  title: "# of downloads",
  data: [{
      'date': new Date('2014-11-01'),
      'value': 12
    },
    {
      'date': new Date('2014-11-02'),
      'value': 9
    }
  ],
  width: 600,
  height: 250,
  color: 'green',
  target: '#chart',
  x_accessor: 'date',
  y_accessor: 'value',
})

In the data property, we have an array of objects with date and value properties, which have the date and the value that corresponds with the date, respectively.

width and height have the dimensions of the graph, color has the value of the color between the line and the x-axis, and x_accessor and y_accessor are the keys from which the x- and y-axes get their values. With the above code, we’d get a line graph that’s green between the line and the x-axis.

Plotly

Plotly is a graphing library that’s available for various runtime environments, including the browser. It supports many kinds of charts and graphs that we can configure with a variety of options.

Support for basic charts like line charts, bar charts, pie charts, and scatter plots are built-in. More complex charts like error bars, box plots, and histograms are also supported. It also has support for rendering maps and 3D charts.

To get started, we just have to include the Plotly library itself. We first add the following HTML:

<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>

<div id="chart"></div>

Then we can add the following JavaScript to create a bar chart:

const data = [{
  x: ['red', 'green', 'blue'],
  y: [12, 9, 3],
  type: 'bar',
  marker: {
    color: ['red', 'green', 'blue']
  }
}];

const layout = {
  title: '# of votes',
};

Plotly.newPlot('chart', data, layout);

The data array has one object, which has the values of the x-axis stored in the x property. The y property has the data for the bar heights.

The type specifies the type of chart to render. In our case, 'bar'specifies that we want to render a bar chart. marker has the color property for the bar colors.

layout is an object that has various layout options. In our example, we set the title property to set the title of the chart, and we get a chart with red, green, and blue displayed, like most of the other examples.

Conclusion

All five of the libraries above let us create charts easily. If we want to create simple 2D charts, then almost all except MetricGraphics can create them — MetricGraphics is mostly confined to creating line charts. Charts like bar charts don’t work properly or are not supported.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...