[Chartjs]-ChartJS: how to make a bar chart with a horizontal guideline:

2👍

You could extend the Bar Chart to add the horizontal line

Chart.types.Bar.extend({
        name: "BarLine",
        draw: function () {

            Chart.types.Bar.prototype.draw.apply(this, arguments);

            var scale = this.scale,
                barHeight = this.scale.calculateY(83);


            // draw line
            this.chart.ctx.beginPath();
            this.chart.ctx.moveTo(30, barHeight);

            this.chart.ctx.strokeStyle = '#ff0000';
            this.chart.ctx.lineWidth = 3;
            this.chart.ctx.lineTo(this.chart.width, barHeight);
            this.chart.ctx.stroke();

            // write Label Text
            this.chart.ctx.fillStyle = '#000000';
            var text = this.options.labelText ? this.options.labelText : "DEFAULT TEXT" 
            this.chart.ctx.textAlign = 'center';
            this.chart.ctx.font = '22px Arial';
            this.chart.ctx.fillText(text, this.chart.width  * 0.5, 95);
            this.chart.ctx.closePath();                            

        }
    });`

You could add the bar values in the draw function i’m sure, but I generally do it in the ‘onanimationcomplete’ function for the chart, like so:

resultChart = new Chart(resultGraphCanvas.getContext("2d")).BarLine(chart, {

                        scaleBeginAtZero: true,
                        scaleOverride: true,
                        scaleSteps: 10,
                        scaleStepWidth: 10,
                        maintainAspectRatio: false,
                        labelText: "TEST DRAWN NEAR THE LINE",

                        showTooltips: false, //Needs to be set to false for the onAnimationComplete drawing to persist
                        onAnimationComplete: function () {


                            var ctx = this.chart.ctx;
                            ctx.font = this.scale.font;
                            ctx.fillStyle = this.scale.textColor
                            ctx.textAlign = "center";
                            ctx.textBaseline = "bottom";

                            this.datasets.forEach(function (dataset) {
                                dataset.bars.forEach(function (bar) {

                                    ctx.fillText(bar.value, bar.x, bar.y );
                                });
                            })
                        },
                    });

This will draw the values at the top of the bars, i’ll leave positioning them elsewhere to you 🙂

Leave a comment