score:56

Accepted answer

you could use the chart.js annotation plugin to easily draw lines on your chart without having to mess with rendering pixels in your canvas manually (the old approach that is giving you errors). note, the plugin is created/supported by the same team as chart.js and is mentioned in the chart.js docs.

here is an example codepen demonstrating creating a line on a chart.

once you add the plugin, you simply just set annotation properties in your chart config. here is an example.

var mychart = new chart(ctx, {
  type: 'line',
  data: {
    labels: ["january", "february"],
    datasets: [{
      label: 'dataset 1',
      bordercolor: window.chartcolors.blue,
      borderwidth: 2,
      fill: false,
      data: [2, 10]
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'chart.js draw line on chart'
    },
    tooltips: {
      mode: 'index',
      intersect: true
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleid: 'y-axis-0',
        value: 5,
        bordercolor: 'rgb(75, 192, 192)',
        borderwidth: 4,
        label: {
          enabled: false,
          content: 'test label'
        }
      }]
    }
  }
});

score:2

here's an example of getting it working in a rails view if you're using it with the chartkick gem:

<%=
  line_chart profit_per_day_chart_path(staff), xtitle: 'day', ytitle: 'profit',
    library: {
      annotation: {
        annotations: [
          {
            type: 'line',
            mode: 'horizontal',
            scaleid: 'y-axis-0',
            value: 20,
            label: {
              content: 'my horizontal line',
              enabled: true
            }
          }
        ]
      }
    }
%>

ensure that you've registered the chartjs-plugin-annotation.js plugin with chart.js first:

import chartannotationsplugin from 'chartjs-plugin-annotation';
chart.plugins.register(chartannotationsplugin);

score:6

if you want to draw threshold line,easiest way is that using mixed line chart.

note: make an array filled with threshold value and the length should be same as your dataset.

var datasets = [1, 2, 3];
var ctx = document.getelementbyid('chart').getcontext('2d');
var thresholdvalue = 2;
var thresholdhigharray = new array(datasets.length).fill(thresholdvalue);
var mychart = new chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                {datasets}, thresholdhigharray]
            },         
            options: {
                responsive: true,
                legend: {
                    position: 'bottom',
                },
                scales: {
                    xaxes: [{
                        display: true,
                        scalelabel: {
                                display: true,
                                labelstring: 'readings'
                        }
                    }],
                    yaxes: [{
                        display: true,
                        scalelabel: {
                                display: true,
                                labelstring: 'reading ( °c )'
                        }
                    }]
                },
                annotation: {
                  annotations: [
                    {
                      type: "line",
                      mode: "vertical",
                      scaleid: "x-axis-0",
                      bordercolor: "red",
                      label: {
                        content: "",
                        enabled: true,
                        position: "top"
                      }
                    }
                  ]
                }
        });
    };

score:6

if you are using the npm package chartjs-plugin-annotation.js, the important thing - which you may forget, is to register the plugin.

so first of all you installed the npm packages (here for react):

npm i react-chartjs-2                (depends on your framework)
npm i chartjs-plugin-annotation      (always required)

see vue.js or angular for their framework depending packages.

option 1: global plugin registration

import { line } from 'react-chartjs-2';
import chart from 'chart.js';
import * as chartannotation from 'chartjs-plugin-annotation';

chart.plugins.register([chartannotation]); // global

// ...
render() {
    return (
        <line data={chartdata} options={chartopts} />
    )
}

option 2: per chart plugin registration

import { line } from 'react-chartjs-2';
import * as chartannotation from 'chartjs-plugin-annotation';

// ...
render() {
    return (
                                                   {/* per chart */}
        <line data={chartdata} options={chartopts} plugins={[chartannotation]} />
    )
}

chartdata is equivalent to the data: { section and chartopts to options: { from jordanwillis answer. see this github post for further information.

there are many other plugins available for chart.js.


Related Query

More Query from same tag