Categories
Chart.js JavaScript React

Create a Line Chart with react-chartjs-2 – an Example

react-chartjs-2 is an easy to use library for creating all kinds of charts.

It’s based on Chart.js, which renders chart in an HTML canvas element.

We can use it to render charts in a canvas inside a React app.

To get started, we install Chart.js and react-chartjs-2 by running:

npm install --save react-chartjs-2 chart.js moment

We also installed moments to create dates for the x-axis labels.

Then we can write the following code:

import React from "react";
import { Line } from "react-chartjs-2";
import moment from "moment";

const startDate = new Date(2020, 0, 1);
const labels = [];
for (let i = 0; i < 6; i++) {
  const date = moment(startDate)
    .add(i, "days")
    .format("YYYY-MM-DD");
  labels.push(date.toString());
}

const data = canvas => {
  const ctx = canvas.getContext("2d");
  const gradient = ctx.createLinearGradient(0, 0, 100, 0);
  return {
    backgroundColor: gradient,
    labels,
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 3,
        fill: false,
        borderColor: "green"
      }
    ]
  };
};

export default function App() {
  return (
    <div className="App">
      <Line data={data} />
    </div>
  );
}

We first create the x-axis labels and populate them in the labels array/

We did that by using the moment function and call add on it to add 1 day in each iteration of the for loop.

Then we create a data function, which takes the canvas object, which has the canvas element as the parameter.

Then we get the canvas from it and change the items that we want.

The function returns the options for our graph, including the data.

The object we return in data has various options.

It has the labels property to populate the x-axis labels.

backgroundColor has the color for our graph.

datasets has an array with an object with the data and some options for the line.

data has the y-axis values for each x-axis value.

borderWidth specifies the thickness of the line in pixels.

fill is set to false means that we don’t have any colors between the x-axis and our line.

label is the text label for our legend.

borderColor is the color of our line.

Once we have that code, we’ll see the following graph:

https://thewebdev.info/wp-content/uploads/2020/05/react-chartjs-2.png

Categories
Chart.js JavaScript

Chart.js – Create a Histogram

We can create a histogram with Chart.js without a problem.

All we have to do is to create a bar chart with some tweaks.

To start, we add Chart.js for the chart and the canvas for Chart.js to render the chart.

We add them by writing the following HTML:

<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>

<canvas id="histogram" width="400" height="400"></canvas>

Next, we create our histogram by writing some JavaScript code:

const ctx = document.getElementById('histogram').getContext('2d');

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [0, 1, 2, 3, 4],
    datasets: [{
      label: 'Number of Arrivals',
      data: [19, 28, 20, 16],
      backgroundColor: 'green',
    }]
  },
  options: {
    scales: {
      xAxes: [{
        display: false,
        barPercentage: 1.3,
        ticks: {
          max: 3,
        }
      }, {
        display: true,
        ticks: {
          autoSkip: false,
          max: 4,
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We render the chart with the canvas element with the ID histogram as we indicated in the code.

In the object that we passed into the Chart constructor, we set the type to 'bar' to display a bar chart.

Then in datasets, we add our data property to set the bar heights.

The labels are the labels that are displayed on the x-axis.

label is displayed above the histogram.

Then we have to adjust the x-axis options by setting ticks maximum to 4 to adjust the ticks.

We make the bars wider than the typical graph by setting barPercentage to 1.3 so that the 4 bars are event distributed between the 5 ticks of the x-axis.

autoSkip set to false means that automatic calculation of how many labels can be shown or hidden is false.

This lets us override the ticks with the ones that we mentioned above.

autoSkip being false means that we always show all labels.

beginAtZero being true means that we start the y-axis at 0.

In the end, we get the following graph:

https://thewebdev.info/wp-content/uploads/2020/04/histogram.png

We can see the green bars and the bar is between 2 ticks rather than the bar being right above each tick.

Categories
Chart.js JavaScript

Chart.js – Creating a Chart with Multiple Lines

To create a chart with multiple lines, we can just create a line chart that display multiple data sets.

To do that, we first start with including the Chart.js library.

Also, we add the moment.js library for formatting dates, and a canvas element for Chart.js to render the chart in.

We do that by writing:

<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>

<canvas id="multipleLineChart" width="400" height="400"></canvas>

Next, we create our chart with multiple lines by writing the following:

const ctx = document.getElementById('multipleLineChart').getContext('2d');

const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [
      moment(new Date(2020, 2, 1)).format('YYYY-MM-DD'),
      moment(new Date(2020, 2, 2)).format('YYYY-MM-DD'),
      moment(new Date(2020, 2, 3)).format('YYYY-MM-DD')
    ],
    datasets: [{
        label: '# of Red Votes',
        data: [12, 18, 22],
        borderWidth: 1,
        fill: false,
        borderColor: 'red'
      },
      {
        label: '# of Green Votes',
        data: [12, 2, 13],
        borderWidth: 1,
        fill: false,
        borderColor: 'green'
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We set the type property to 'line' to display line charts.

Then we have the labels property to display the labels for the x-axis.

In the datasets property, we set the value to an array.

The array has the data property to set the y-axis value for where the dot is displayed.

We set the fill property to false so that we don’t get any filling between the line and the x-axis.

borderColor has the color value of the line. We set one to 'red' and the other to 'green'.

In the options property, we set the beginAtZero property to true so that the y-axis begins at zero.

Once we write that code, we get a chart with multiple lines with one being red and the other being green.

It looks like:

https://thewebdev.info/wp-content/uploads/2020/04/multiplelines.png

Categories
Chart.js JavaScript

Create a Grouped Bar Chart with Chart.js

We can make a grouped bar chart with Chart.js by creating a bar chart that has multiple datasets entries.

To start, we first include the Chart.js library. We also include the moment.js library for formatting dates.

The grouped bar chart will be rendered in a canvas element.

So we write the following code to include all that:

<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>

<canvas id="barChart" width="400" height="400"></canvas>

Next, we add the code for rendering the grouped bar chart.

We write the following:

const ctx = document.getElementById('barChart').getContext('2d');

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [
      moment(new Date(2020, 1, 1)).format('YYYY-MM-DD'),
      moment(new Date(2020, 1, 2)).format('YYYY-MM-DD'),
      moment(new Date(2020, 1, 3)).format('YYYY-MM-DD')
    ],
    datasets: [{
        label: '# of Red Votes',
        data: [12, 18, 22],
        borderWidth: 1,
        backgroundColor: ['red', 'red', 'red']
      },
      {
        label: '# of Green Votes',
        data: [12, 2, 13],
        borderWidth: 1,
        backgroundColor: ['green', 'green', 'green']
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The code above has the labels property with the labels for the x-axis.

The datasets property has the data sets we display on the y-axis.

data has the bar heights for each bar.

label has the label for each bar.

backgroundColor has the background color for each bar.

borderWidth has the border width for each bar.

Then in the options property, we have the beginAtZero property to make sure that the y-axis starts at zero instead of the value of the lowest bar value.

In the end, we have:

https://thewebdev.info/wp-content/uploads/2020/04/groupedbar.png

It’s a grouped bar chart with red and green bars displaying the data in the data arrays.

With Chart.js, creating a grouped bar chart is just a matter of setting the labels, bar heights, and bar colors of each bar.

Categories
Chart.js JavaScript

Create a Stack Bar Chart with Chart.js

We can create stacked bar chart with Chart.js

With the stacked option in Chart.js, we can create a stacked bar chart from a simple bar chart.

To create the chart, first we need to add Chart.js to our code by writing:

<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>

<canvas id="barChart" width="400" height="400"></canvas>

The code above also adds moment.js for manipulating time and a canvas element to display the chart.

Then we write:

const ctx = document.getElementById('barChart').getContext('2d');

const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [
      moment(new Date(2020, 0, 1)).format('YYYY-MM-DD'),
      moment(new Date(2020, 0, 2)).format('YYYY-MM-DD'),
      moment(new Date(2020, 0, 3)).format('YYYY-MM-DD')
    ],
    datasets: [{
        label: '# of Green Votes',
        data: [12, 19, 13],
        borderWidth: 1,
        backgroundColor: ['green', 'green', 'green']
      },
      {
        label: '# of Pink Votes',
        data: [15, 9, 19],
        borderWidth: 1,
        backgroundColor: ['pink', 'pink', 'pink']
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});

We’ve specified by the labels in the labels property to be 3 dates.

In the datasets property, we have the label to display the label of the legtnd.

The borderWidth has the border with value of the bar in pixels.

The backgroundColor has the background color of the bars.

The data has the bar heights of the bars.

The options object has the property that lets us create a stacked bar chart.

We have the xAxes property, which has an array with an object that has stacked set to true.

Also, we have the same property in the object in the yAxes array.

Once we have that, we get:

https://thewebdev.info/wp-content/uploads/2020/04/stackedbar.png

Creating a stacked bar chart is just as easy as add the data to display for each bar.

Then we set the stacked option in the options object to make 2 or more bars stacked together.