Draw horizontal line on chart in chart.js on v2

Related searches

I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code

function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
    labels: data.labels,
    datasets: [
        {
            label: label,
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        }
    ]
};

//options
var options = {
    responsive: true,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    }
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});}

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'
        }
      }]
    }
  }
});

chart.js, Example#. Create horizontal lines with a label. This could be used to show notable values in the chart data (e.g. min, max, average). JSFiddle Demo How to fill the area under the line. See area charts. lineTension: Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used. showLine: If false, the line is not drawn for this dataset. spanGaps: If true, lines will be drawn between points with no or null data.

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"
                      }
                    }
                  ]
                }
        });
    };

Chart.js Horizontal line on line chart, Analyze HTML; Maximize HTML Editor; Minimize HTML Editor; Fold All; Unfold All. xxxxxxxxxx. 3. 1. <div style="width: 75%">. 2. <canvas id="canvas"></canvas> . If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn. drawTicks: boolean: true: If true, draw lines beside the ticks in the axis area beside the chart. tickMarkLength: number: 10: Length in pixels that the grid lines will draw into the axis

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.

Mixed � Chart.js documentation, With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types. A common example is a bar chart that also includes a line dataset. By default, datasets are drawn so that first one is top-most. 10, 10, 10], type: 'line', // this dataset is drawn on top order: 2 }], labels: ['January',� Creating a Material Line Chart is similar to creating what we'll now call a "Classic" Line Chart. You load the Google Visualization API (although with the 'line' package instead of the 'corechart' package), define your datatable, and then create an object (but of class google.charts.Line instead of google.visualization.LineChart).

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);

Line � Chart.js documentation, The line chart allows a number of properties to be specified for each dataset. These are this dataset on. yAxisID, The ID of the y axis to plot this dataset on. Clipping can also be configured per side: clip: {left: 5, top: false, right: -2, bottom: 0}. The global line chart settings are stored in Chart.defaults.line. Changing the global options only affects charts created after the change. Existing charts are not changed. For example, to configure all line charts with spanGaps = true you would do: Chart.defaults.line.spanGaps = true; Data Structure. The data property of a dataset for a line

Simple, clean and engaging HTML5 based JavaScript charts. Chart.js is an easy way to include animated, interactive graphs on your website for free.

The configuration options for the horizontal bar chart are the same as for the bar chart. However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart. Internal data format# {x, y, _custom} where _custom is optional object defining stacked bar properties: {start, end, barStart, barEnd, min, max}.

This is a list of 10 working graphs (bar chart, pie chart, line chart, etc.) with colors and data set up to render decent looking charts that you can copy and paste into your own projects, and quickly get going with customizing and fine-tuning to make them fit your style and purpose. To use these examples, make sure to also include Chart.js:

Comments
  • Are you getting any errors? Can you describe what is happening? It could be a simple issue of chart.js versioning. This solution targets chart.js v2.3.0 (the latest version at the time the question was answered), however some options and APIs have changed in the latest version (v2.7.1).
  • Now Resolved: stackoverflow.com/questions/47655173/…. Thanks Jordan !