DEV Community

Cover image for 5 top picks for JavaScript chart libraries
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

5 top picks for JavaScript chart libraries

Written by John Au-Yeung✏️

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>
Enter fullscreen mode Exit fullscreen mode

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
        }
      }]
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

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 yAxes to set some options for the y-axis, and we specified beginAtZero to true so that the y-axis begins at 0.

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

LogRocket Free Trial Banner

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 bindto property 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
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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',
})
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Plotly, on the other hand, offers support for most kinds of charts. It also has a Python library, so we can use it in Python programs as well as webpages.


LogRocket: Debug JavaScript errors easier by understanding the context

Debugging code is always a tedious task. But the more you understand your errors the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to find out exavtly what the user did that led to an error.

LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier.

Try it for free.


The post 5 top picks for JavaScript chart libraries appeared first on LogRocket Blog.

Top comments (0)