Categories
Chart.js JavaScript Answers

How to Add Grouped Bar Charts with Chart.js?

Sometimes, we want to add grouped bar charts with Chart.js.

In this article, we’ll look at how to add grouped bar charts with Chart.js.

Add Grouped Bar Charts with Chart.js

To add grouped bar charts with Chart.js, we just have to put all the chart data in the datasets array property.

For instance, we can add the Chart.js script and the canvas for the chart with the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

to get the canvas 2d context with:

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

Then chart data is defined with:

const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

Each entry has the data for each bar.

They’ll be grouped together into a group bar chart with Chart.js.

Then we create our chart with:

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

We just set type to 'bar' to create a grouped bar chart.

Conclusion

To add grouped bar charts with Chart.js, we just have to put all the chart data in the datasets array property.

Categories
Chart.js JavaScript Answers

How to Hide Decimal Points on Numbers on the Y-Axis in Chart.js?

Sometimes, we want to hide decimal points on numbers on the y-axis in Chart.js.

In this article, we’ll look at how to hide decimal points on numbers on the y-axis in Chart.js.

Hide Decimal Points on Numbers on the Y-Axis in Chart.js

To hide decimal points on numbers on the y-axis in Chart.js, we can set the stepSize option.

For instance, we can write the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

to add the Chart.js script and the canvas for the chart.

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        ticks: {
          stepSize: 1,
          beginAtZero: true,
        },
      },
    },
  }
});

to create the chart.

We set the options.scales.y.ticks.stepSize property to 1 so the numbers on the y-axis will always be integers with no trailing decimal.

Conclusion

To hide decimal points on numbers on the y-axis in Chart.js, we can set the stepSize option.

Categories
Chart.js JavaScript Answers

How to Handle Click Events on Charts in Chart.js?

Sometimes, we want to handle click events on charts in Chart.js.

In this article, we’ll look at how to handle click events on charts in Chart.js.

Handle Click Events on Charts in Chart.js

To handle click events on charts in Chart.js, we can add the onClick method into our chart.

Then we can use the getElementsAtEventForNode method to get the index of the data set entry that we clicked on.

For instance, we can write the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>

to add the script for Chart.js and canvas elements for the bar chart.

Then we can add the bar chart by writing:

const datasets = [{
  label: '# of Votes',
  data: [12, 19, 3, 5, 2, 3],
  backgroundColor: [
    'rgba(255, 99, 132, 0.2)',
    'rgba(54, 162, 235, 0.2)',
    'rgba(255, 206, 86, 0.2)',
    'rgba(75, 192, 192, 0.2)',
    'rgba(153, 102, 255, 0.2)',
    'rgba(255, 159, 64, 0.2)'
  ],
  borderColor: [
    'rgba(255,99,132,1)',
    'rgba(54, 162, 235, 1)',
    'rgba(255, 206, 86, 1)',
    'rgba(75, 192, 192, 1)',
    'rgba(153, 102, 255, 1)',
    'rgba(255, 159, 64, 1)'
  ],
  borderWidth: 1
}]

const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    onClick(e) {
      const activePoints = myChart.getElementsAtEventForMode(e, 'nearest', {
        intersect: true
      }, false)
      const [{
        index
      }] = activePoints;
      console.log(datasets[0].data[index]);
    }
  }
});

We have the datasets array with the data, border color, and bar colors we want to display.

Also, we have the label to set the label of the legend.

Next, we have the options property set to an object with the onClick method to catch any clicks that were made on the chart.

In it, we call myChart.getElementsAtEventForNode method with the e event object, 'nearest' and an object with intersect set to true to get the nearest object that’s been clicked on.

It returns an array with the index of the dataset data entry that we clicked on.

Then we can get the value of the bar that we clicked on with:

datasets[0].data[index]

Conclusion

To handle click events on charts in Chart.js, we can add the onClick method into our chart.

Then we can use the getElementsAtEventForNode method to get the index of the data set entry that we clicked on.

Categories
Chart.js

Chart.js — Time and Radial Axes Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Time Axis Scale Bounds

We can change the bounds property to control the scale boundary strategy.

It can either be 'data' or 'ticks' .

'data' makes sure data are fully visible.

'ticks' makes sure ticks are fully visible.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        bounds: 'data'
      }]
    }
  }
});

to display the ticks according to the available data so that they’re visible.

Ticks Source

The ticks.source property controls the tick generation.

The value can be 'auto' , 'data' or 'labels' .

'auto' generates the optimal ticks based on scale size and time options.

'data' generates ticks from data.

'labels' generate ticks from the user given labels only.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        ticks: {
          source: 'auto'
        }
      }]
    }
  }
});

to let Chart.js generate the optimal ticks.

Linear Radial Axis

Radial axes are used to specify the radar and polar area chart types.

A linear scale is used to chart numeric data.

Linear interpolation is used to determine where value lies in relation to the center of the axis.

We can change the axis range settings with the ticks.suggestedMin and ticks.suggestedMax properties.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'radar',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scale: {
      ticks: {
        suggestedMin: 50,
        suggestedMax: 100
      }
    }
  }
});

to change the suggested min and max values.

This way, we can change the scale values to be different from the default.

Radial Axis Step Size

We can also change the step size.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'radar',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scale: {
      ticks: {
        max: 60,
        min: 0,
        stepSize: 0.5
      }
    }
  }
});

We set the max and min values for the axes with those properties.

And stepSize changes the tick size for the radial axes.

Conclusion

We can change the time axis to what we want.

Also, we can change the radial axis lines.

Categories
Chart.js

Chart.js — Axis Labels and Instance Methods

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Labeling Axes

The labeling axis tells the viewer what they’re viewing.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          callback(value, index, values) {
            return `$${value}`;
          }
        }
      }]
    }
  }
});

We put a dollar before the number with the callback .

value has the y-axis value.

Styling

We can style an axis with various options.

For instance, we can change the color, border, ticks, and more of the grid lines.

We can do that by changing the gridLines property.

To do that, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        gridLines: {
          color: 'green'
        }
      }]
    }
  }
});

We change the gridLine color to 'green' .

There are also other options like the zero line width, zero line color, border dash, and more.

Tick Configuration

We can also change the tick configuration.

To do this, we can change the ticks property.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          fontColor: 'green'
        }
      }]
    }
  }
});

We change the y-axis ticks with the font color to 'green' to make the y-axis labels green.

Other options include font style, line weight, padding, and more.

There’re also options for minor and major ticks.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          minor: {
            fontColor: 'green'
          },
          major: {
            fontColor: 'red'
          }
        }
      }]
    }
  }
});

to change the minor and major tick options.

The full list of options is at https://www.chartjs.org/docs/latest/axes/styling.html.

Chart Prototype Methods

Each Chart instance has its own instance methods.

They include:

  • destroy — destroys the chart
  • reset — resets the chart to the state before the initial animation.
  • render(config) — render a config with various options.
  • stop — stop any current animation loop
  • resize — resize a chart’s canvas element
  • clear — clear the chart canvas
  • toBase64Image — returns the base64 encoded string of the chart in its current state
  • generateLegend — returns an HTML string of a legend for the chart
  • getElementAtEvent(e) — get element based on the event object.
  • getElementsAtEvent(e) — get elements based on the event object.
  • getDatasetAtEvent(e) — get element under the went point.
  • getDatasetMeta(index) — get a dataset that matches the current index and returns the metadata.

Conclusion

We can call instance methods on a chart.

Also, the labels can be changed the way we want.