How to draw horizontal Lines using chart.js 3.x ? Cannot get it working

5.4k Views Asked by At

Goal

I would like to create a graph comprising of three horizontal lines overlaying my actual dataset line using Chart.js 3.x by CDN integration in my html page.

So, I have no own Chart.js installation but am using CDNs. So far, I had no real issues using the very latest Chart.js 3.x Beta version in such manner.

Important note: As I need some of it's additional Beta features, I cannot revert to stable Chart.js 2.x.

Expected result

That's how it should like alike.

Actual result

I have no issue creating the actual line graph based on my dataset using Chart.js version 3.0.0-beta.6. If you comment line 64 of the JavaScript Fiddle section, you will see the basic graph working.

But, unfortunately, I cannot get the horizontal lines graphed!

What I have tried so far

Jsfiddle - not working attempt

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>

  <style>
    .container{
      position: relative;
      width: 50vw;
    }
  </style>
</head>
<body>
  <canvas id="myChart" class="container"></canvas>

<script>
  var canvas = document.getElementById("myChart");
  var ctx = canvas.getContext("2d");

  var horizonalLinePlugin = {
    id: 'horizontalLine',
    afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    }
  }
};


var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "MyDataset01",
    fill: false,
    lineTension: 0.1,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    data: [65, 59, 80, 81, 56, 55, 40],
  }]
};

//When uncommenting below line, graph is created without horizontal lines
Chart.register(horizonalLinePlugin);
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 75.8,
      "style": "#ff0000",
      "text": "upper-limit"
    }, {
      "y": 62.3,
      "style": "#00ff00",
      "text": "avg"
    }, {
      "y": 48.8,
      "style": "#0000ff",
      "text": "lower-limit"
    }]
  }
});
</script>

I read documentation of Chart.js and working examples of chartjs-annotation-plugin - but all unfortunately only based on Chart.js versions 2.x.

I did not manage to get it working trying shortly CDNs https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js and https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js together. Did not find any working e.g. Fiddle example.

And now I tried using an inline Chart.js plugin without success, getting e.g. error message

Line 8 in JavaScript section of Fiddle: "#55:15 TypeError: canvas is undefined"

3

There are 3 best solutions below

0
On BEST ANSWER

Plugins are a very common way to add custom functionality to ChartJS. It allows us to manipulate event, using hooks offered by a plugin object.

In this simple example, we will create a plugin with ID horizontalLines. Then, we will call the afterDraw hook to render horizontal lines, which is called after the chart has been rendered.

const $canvas = document.getElementById('chart')

const plugin = {
    id: 'horizontalLines',
    defaults: {
        lines: []
    },
    afterDraw: (chart, _, options) => {
        const { ctx } = chart
        const { left, right } = chart.chartArea

        const lines = options.lines
        if (!lines) return
        for (const line of lines) {
            const scale = chart.scales.y
            
            const width = line.width || 1
            const color = line.color || 'rgba(169,169,169, .6)'
            const value = line.value ? scale.getPixelForValue(line.value) : 0
            const label = line.label || null

            if (value) {
                ctx.beginPath()
                ctx.lineWidth = width
                ctx.moveTo(left, value)
                ctx.lineTo(right, value)
                ctx.strokeStyle = color
                ctx.stroke()
            }

            if (label) {
                ctx.fillStyle = color
                ctx.fillText(label, right - label.length*5, value + width)
            }
        }

        return
    }
}



const data = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
        data: [65, 59, 80, 81, 56, 55, 40],
        label: 'Dataset01',
        fill: false,
        lineTension: 0.1,
        backgroundColor: 'rgba(75,192,192,0.4)',
        borderColor: 'rgba(75,192,192,1)',
    },]
}

Chart.register(plugin)

const chart = new Chart($canvas, {
    type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
        plugins: {
            'horizontalLines': {
                lines: [{
                    value: 75.8,
                    color: 'red',
                    label: 'upper',
                },
                {
                    value: 62.3,
                    color: 'lime',
                    label: 'avg',
                },
                {
                    value: 48.8,
                    color: 'blue',
                    label: 'lower',
                }]
            },
        },
    }
})
.container {
  position: relative;
  width: 90vw;
}
<div class="container">
  <canvas id="chart"></canvas>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

2
On

chartInstance.chart is undefined. Not sure is that a migration issue to chart.js ver 3.0...

Try the following:

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.6/chart.js"></script>

  <style>
    .container{
      position: relative;
      width: 50vw;
    }
  </style>
</head>
<body>
  <canvas id="myChart" class="container"></canvas>

<script>
  var canvas = document.getElementById("myChart");
  var ctx = canvas.getContext("2d");

  var horizonalLinePlugin = {
    id: 'horizontalLine',
    afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y"];

    // chartInstance.chart is undefined
    //var canvas = chartInstance.chart;
   // console.log(canvas);
   // var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    }
  }
};


var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "MyDataset01",
    fill: false,
    lineTension: 0.1,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    data: [65, 59, 80, 81, 56, 55, 40],
  },
]
};
//When uncommenting below line, graph is created without horizontal lines
Chart.register(horizonalLinePlugin);
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 75.8,
      "style": "#ff0000",
      "text": "upper-limit"
    }, {
      "y": 62.3,
      "style": "#00ff00",
      "text": "avg"
    }, {
      "y": 48.8,
      "style": "#0000ff",
      "text": "lower-limit"
    }],

    
   
  }
});
</script>

here is the code above in Jsfiddle - working!

0
On

I was facing the same issue when using chartjs 3.0. I used the following code to get the horizontal line displayed

var horizonalLinePlugin = {
id : 'horizontalLine',
afterDraw: function (chartInstance) {
    // var yScale = chartInstance.scales["y-axis-0"];
    var yScale = chartInstance.scales['y'];
    // var canvas = chartInstance.chart;
    var canvas = chartInstance.canvas;
    var ctx = chartInstance.ctx;
    var index;
    var line;
    var style;
    var yValue;

    if (chartInstance.config._config.options.horizontalLine) {
        for (index = 0; index < chartInstance.config._config.options.horizontalLine.length; index++) {
            line = chartInstance.config._config.options.horizontalLine[index];

            if (!line.style) {
                style = "rgba(169,169,169, .6)";
            } else {
                style = line.style;
            }

            if (line.y) {
                yValue = yScale.getPixelForValue(line.y);
            } else {
                yValue = 0;
            }

            ctx.lineWidth = 3;

            if (yValue) {
                ctx.beginPath();
                ctx.moveTo(20, yValue);
                // ctx.moveTo(0, yValue);
                ctx.lineTo(canvas.width, yValue);
                ctx.strokeStyle = style;
                ctx.stroke();
            }

            if (line.text) {
                ctx.fillStyle = style;
                ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
            }
        }
        return;
    };
}
};
Chart.register(horizonalLinePlugin);