Chartjs Point with Vertical Line post

Chartjs point with vertical line

In my journey to adapt Chart.js to fit some of my requirements, I had to draw some points of interest in a line chart and draw a vertical line to the baseline.

The Chartjs plugin system came to my rescue again (see my previous post).

Plugins are the most efficient way to customize or change the default behavior of a chart, but there are not so many examples out there, so I am bringing another one.

In this line chart I am using a dataset type "scatter" to draw some points of interest in the line dataset, then for these specific point I wish to draw a vertical line from the scatter point to the chart base.

To perform this task, I created the following plugin to implement the hook "afterDatasetDraw" and draw a vertical line if the dataset is "scatter" type:

    var VerticalLinePlugin = {
        afterDatasetDraw: function (chart, params) {
            // Only draw after animation has finished and is the desired dataset
            if(params.easingValue == 1 && params.meta.type == "scatter") {
                var ctx = chart.ctx;
       => {
                    var model = point._model;
                    ctx.strokeStyle = point._options.borderColor;
                    ctx.lineWidth = point._options.borderWidth;
                    ctx.moveTo(model.x, model.y);
                    ctx.lineTo(model.x, chart.chartArea.bottom);

Insert the custom plugin in the Chart configuration to make it work:

Categories: programming

Tags: chartjs, javascript, tips