Categories
Chart.js JavaScript Answers

How to 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.

Categories
Chart.js JavaScript Answers

How to 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]
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.

Categories
Chart.js

Chart.js — Titles and Legends

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.

Legend Item Options

There are many options we can change to configure the legend.

The text has the label text.

fillStyle has the fill style of the legend box.

lineCap is a string with the box border CSS.

lineDash is a number array for the canvas box border.

lineDashOffset has the canvas box border offset.

lineJoin has the canvas context lineJoin property value.

lineWidth has the width of the box border.

strokeStyle has the color of the strokes for the legend.

pointStyle has the point style for the legend box.

rotation has the rotation of the point in degrees.

For example, we can link the display of 2 datasets by writing:

var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function(e, legendItem) {
  var index = legendItem.datasetIndex;
  if (index > 1) {
    defaultLegendClickHandler(e, legendItem);
  } else {
    let ci = this.chart;
    [
      ci.getDatasetMeta(0),
      ci.getDatasetMeta(1)
    ].forEach(function(meta) {
      meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
    });
    ci.update();
  }
};

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1
    }, {
      label: '# of Votes',
      data: [10, 19, 3],
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      onClick: newLegendClickHandler
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The else block calls update on both datasets.

If one isn’t hidden as indicated with

meta.hidden === null

Then the other bars will also be shown with:

!ci.data.datasets[index].hidden

And we call ci.update to update the chart.

Then we use this function as the value of the options.legend.onClick property to toggle both bars on and off if we click on the legend.

HTML Legends

We can also add the legendCallback property to render an HTML legend.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    legendCallback(chart) {
      //...
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

Title

We can change the way the chart title is rendered at the top of the chart.

For instance, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Chart Title'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to set the options.title.text property to set the options text.

Conclusion

We can change the title and legend options with a few properties.