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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...