Advertisement
  1. Code
  2. JavaScript

Getting Started With Chart.js: Line and Bar Charts

Scroll to top
This post is part of a series called Getting Started With Chart.js.
Getting Started With Chart.js: Introduction
Getting Started With Chart.js: Radar and Polar Area Charts

In the first introductory Chart.js tutorial of the series, you learned how to install and use Chart.js in a project. You also learned about some global configuration options that can be used to change the fonts and tooltips of different charts. In this tutorial, you will learn how to create line and bar charts in Chart.js.

Creating Line Charts

Line charts are useful when you want to show the changes in value of a given variable with respect to the changes in some other variable. The other variable is usually time. For example, line charts can be used to show the speed of a vehicle during specific time intervals.

Chart.js allows you to create line charts by setting the type key to line. Here is an example:

1
let lineChart = new Chart(speedCanvas, {
2
    type: 'line',
3
    data: speedData
4
});

We will now be providing the data that we need to plot the line chart.

1
let speedData = {
2
  labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
3
  datasets: [{
4
    label: "Car Speed (mph)",
5
    data: [0, 59, 75, 20, 20, 55, 40],
6
  }]
7
};

Since we have not provided any color for the line chart, the default color rgba(0,0,0,0.1) will be used. We have not made any changes to the tooltip or the legend. You can read more about changing the crate size, the tooltip, or the legend in the first part of the series.

In this part, we will be focusing on different options specifically available for modifying line charts. All the options and data that we provided above will create the following chart. The above code is the absolute minimum that you need to provide in order to create a line chart. It will create the chart shown below.

The color of the area under the curve is determined by the backgroundColor key, and it is set to rgba(0, 0, 0, 0.1) by default. All the line charts drawn using this method will be filled with the given color. However, you will also need to make sure that the value of the fill key is set to true for the background color to be visible. It is set to false by default.

One more thing that you might have noticed is that we are using discrete data points to plot the chart. The library automatically interpolates the values of all other points by using built-in algorithms.

By default, the points are plotted with linear interpolation of values. This means that the different segments of our line chart will always be a straight line. Passing a non-zero value for the tension key will result in a custom weighted cubic interpolation to determine the trajectory of the line chart between our plot points.

You can also set the value of the cubicInterpolationMode key to monotone to plot points more accurately when the chart you are plotting is defined by the equation y = f(x). The value of the tension key is ignored in monotone mode, and the library makes sure that the points you are plotting are extremum values in their vicinity. For example, the line will never go above the highest plotted point or below the lowest plotted point.

You can also set the value of the border color and its width using the borderColor and borderWidth keys. If you want to plot the chart using a dashed line instead of a solid line, you can use the borderDash key. It accepts an array as its value, and the array's elements determine the length and spacing of the dashes.

The appearance of the plotted points can be controlled using the pointBorderColor, pointBackgroundColor, pointBorderWidth, pointRadius, and pointHoverRadius properties. There is also a pointHitRadius key, which determines the distance at which the plotted points will start interacting with the mouse.

1
let speedData = {
2
  labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
3
  datasets: [{
4
    label: "Car Speed (mph)",
5
    data: [0, 59, 75, 20, 20, 55, 40],
6
    cubicInterpolationMode: 'monotone',
7
    fill: false,
8
    borderColor: '#E64A19',
9
    backgroundColor: 'transparent',
10
    borderDash: [20, 10, 60, 10],
11
    pointBorderColor: '#E64A19',
12
    pointBackgroundColor: '#FFA726',
13
    pointRadius: 5,
14
    pointHoverRadius: 10,
15
    pointHitRadius: 30,
16
    pointBorderWidth: 4,
17
    pointStyle: 'rectRounded'
18
  }]
19
};

The above speedData object plots the same data points as the previous chart but with custom values set for a lot of the properties. Please note that the value of the tension key specified in the CodePen demo is irrelevant because cubicInterpolationMode is set to monotone. I have included it here so that you can experiment with different values after changing the interpolation mode to default.

Chart.js also gives you the option to avoid any kind of interpolation between different points and just abruptly change the values in steps. The plot will just consist of horizontal and vertical lines in this case. You simply have to set the value of the stepped key to true to achieve this effect. There are also some other possible values, like middle, which will result in the creation of the step in the middle of two plotted points.

The segments between different points of the same dataset can have their own unique styling applied to them. Segment styling currently works for all border* properties as well as the backgroundColor property. The segment key accepts an object which can contain callback functions to determine the value of different properties like borderColor. I will show you how to do that in the following example, where we plot the speed of two different cars on the graph.

1
const checkSpeed = (ctx, color_a, color_b) => ctx.p0.parsed.y > ctx.p1.parsed.y ? color_a : color_b;
2
3
let dataFirst = {
4
  label: "Car A - Speed (mph)",
5
  data: [0, 59, 75, 20, 20, 55, 40],
6
  borderColor: "black",
7
  backgroundColor: "transparent",
8
  borderDash: [3, 3],
9
  stepped: "middle"
10
};
11
12
let dataSecond = {
13
  label: "Car B - Speed (mph)",
14
  data: [20, 15, 60, 60, 65, 30, 70],
15
  borderColor: "blue",
16
  backgroundColor: "transparent",
17
  segment: {
18
        borderColor: ctx => checkSpeed(ctx, 'orangered', 'yellowgreen'),
19
  },
20
};
21
22
let speedData = {
23
  labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
24
  datasets: [dataFirst, dataSecond]
25
};
26
27
let lineChart = new Chart(speedCanvas, {
28
  type: "line",
29
  data: speedData
30
});

We have defined two functions which compare the value of the current and next plot point. If the current speed is higher, this means the car is slowing down and we set the borderColor to orangered. Otherwise, the color stays yellowgreen.

Creating Bar Charts

Bar charts are useful when you want to compare a single metric for different entities—for example, the number of cars sold by different companies or the number of people in certain age groups in a town. You can create bar charts in Chart.js by setting the type key to bar. By default, this will create charts with vertical bars.

1
let barChart = new Chart(densityCanvas, {
2
    type: 'bar',
3
    data: densityData
4
});

Let's create a bar chart which plots the density of all the planets in our solar system. The density data has been taken from the Planetary Fact Sheet provided by NASA.

1
let densityData = {
2
  label: 'Density of Planets (kg/m3)',
3
  data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638]
4
};
5
let barChart = new Chart(densityCanvas, {
6
  type: 'bar',
7
  data: {
8
    labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
9
    datasets: [densityData]
10
  }
11
});

The parameters provided above will create the following chart:

Just like the line chart, the bars are filled with a light gray color this time as well. You can change the color of the bars using the backgroundColor key. Similarly, the color and width of the borders of different bars can be specified using the borderColor and borderWidth keys.

If you want the library to skip drawing the border for a particular edge, you can specify that edge as a value of the borderSkipped key. You can set its value to top, left, bottom, or right. You can also change the border and background color of different bars when they are hovered over by using the hoverBorderColor and hoverBackgroundColor key.

The bars in the bar chart above were sized automatically. However, you can control the width of individual bars using the barThickness and barPercentage properties. The barThickness key is used to set the thickness of bars in pixels, and barPercentage is used to set the thickness as a percentage of the available category width.

You can also show or hide a particular axis using its display key. Setting the value of display to false will hide that particular axis. You can read more about all these options on the documentation page.

You can also create horizontal bar charts with Chart.js. Since they look very similar to regular vertical bar charts, all you need to do is set the value of the indexAxis key to y.

Let's make the density chart more interesting by overriding the default values for bar charts using the following code.

1
let densityData = {
2
  label: "Density of Planets (kg/m3)",
3
  data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638],
4
  backgroundColor: "pink",
5
  borderColor: "red",
6
  borderWidth: 2,
7
  hoverBorderWidth: 5,
8
  hoverBackgroundColor: "darkgray",
9
  hoverBorderColor: "black",
10
  indexAxis: "y",
11
  barPercentage: 1.1
12
};
13
14
let barChart = new Chart(densityCanvas, {
15
  type: "bar",
16
  data: {
17
    labels:["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"],
18
    datasets: [densityData]
19
  }
20
});

The parameters provided above will create the following bar chart.

You can also plot multiple datasets on the same chart by assigning an id of the corresponding axis to a particular dataset. The xAxisID key is used to assign the id of any x-axis to your dataset. Similarly, the yAxisID key is used to assign the id of any y-axis to your dataset. Both the axes also have an id key that you can use to assign unique ids to them.

If the last paragraph was a bit confusing, the following example will help clear things up.

1
let gravityBars = '#F06292';
2
let densityBars = '#4DB6AC';
3
4
let densityData = {
5
  label: "Density of Planet (kg/m3)",
6
  data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638],
7
  backgroundColor: densityBars,
8
  yAxisID: "y-axis-density"
9
};
10
11
let gravityData = {
12
  label: "Gravity of Planet (m/s2)",
13
  data: [3.7, 8.9, 9.8, 3.7, 23.1, 9.0, 8.7, 11.0],
14
  backgroundColor: gravityBars,
15
  yAxisID: "y-axis-gravity"
16
};
17
let planetData = {
18
  labels: [ "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
19
  datasets: [densityData, gravityData]
20
};
21
22
let chartOptions = {
23
  barPercentage: 1,
24
  categoryPercentage: 0.8,
25
  scales: {
26
    "y-axis-density": {
27
      grid: {
28
        color: densityBars,
29
        tickColor: densityBars,
30
        borderColor: densityBars
31
      },
32
      ticks: {
33
        color: densityBars
34
      },
35
      position: "left"
36
    },
37
    "y-axis-gravity": {
38
      grid: {
39
        color: gravityBars,
40
        tickColor: gravityBars,
41
        borderColor: gravityBars
42
      },
43
      ticks: {
44
        color: gravityBars
45
      },
46
      position: "right"
47
    }
48
  }
49
};
50
51
let barChart = new Chart(densityCanvas, {
52
  type: "bar",
53
  data: planetData,
54
  options: chartOptions
55
});

Here, we have created two y-axes with unique ids, and they have been assigned to individual datasets using the yAxisID key. We use these unique ids inside the chartOptions object to specify different grid, tick, and border color values for the axes. This makes our charts much more legible.

The barPercentage and categoryPercentage keys have been used here to group the bars for individual planets together. Setting categoryPercentage to a lower value increases the space between the bars of different planets. Similarly, setting barPercentage to a higher value reduces the space between bars of the same planet.

Final Thoughts

In this tutorial, we have covered all the major aspects of line charts and bar charts in Chart.js. You should now be able to create basic charts, modify their appearance, and plot multiple datasets on the same chart without any issues. In the next part of the series, you will learn about the radar and polar area charts in Chart.js.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.