Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chartjs - Drawing vertical line on integer x axis value

Tags:

chart.js

In the below example, the chartjs annotation works with a string value ("MAR"), but not with an integer value. How do I draw a vertical line on some integer x-axis value.

var chartData = {
  labels: ["JAN", "FEB", "MAR"],
  datasets: [
    {
      data: [12, 3, 2]
    }
  ]
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  new Chart(ctx, {
    type: "line",
    data: chartData,
    options: {
      annotation: {
        annotations: [
          {
            type: "line",
            mode: "vertical",
            scaleID: "x-axis-0",
            value: 2,
            borderColor: "red",
            label: {
              content: "TODAY",
              enabled: true,
              position: "top"
            }
          }
        ]
      }
    }
  });
};

See fiddle: https://codepen.io/anon/pen/QaQWba

like image 241
maged Avatar asked Jan 09 '18 05:01

maged


People also ask

How do you draw a vertical line in Chartjs?

Use two y-axes: one for the bar chart (which we don't display), and one for all your other line chart datasets. Force the bar chart y-axes to min: 0 and max: 1 . Anytime you want to draw a vertical line, add a data object like { x: where_the_line_goes, y: 1 } to your bar chart dataset.

How do I remove a dot in Chartjs?

You can set the pointRadius to zero. I've added "borderWidth: 1" and "pointRadius: 0.5" because I also needed a fine line and tiny dots to hover over them. I needed to add pointHitRadius: 0 as well to disable tooltips.


1 Answers

You can achieve your goal passing data as points, configuring xAxes as linear and creating a custom tick format:

Data:

var chartData = {
  labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
  datasets: [
    {
      data: [{x: 1, y: 12}, {x: 2, y: 3}, {x: 3, y: 2}, {x: 4, y: 1}, {x: 5, y: 8}, {x: 6, y: 8}, {x: 7, y: 2}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 5}, {x: 11, y: 11}, {x: 12, y: 1}];
    }
  ]
};

xAxes config:

xAxes: [{
  type: 'linear',
  position: 'bottom',
  ticks: {
        max: 12,
        min: 1,
        stepSize: 1,
        callback: function(value, index, values) {
             return chartData.labels[index];
        }
   }
}]

Check the CodePen updated: https://codepen.io/beaver71/pen/XVZXOM

like image 104
beaver Avatar answered Sep 21 '22 08:09

beaver