Chart.js: Get data point positions?

Created on 3 May 2016  路  7Comments  路  Source: chartjs/Chart.js

I am attempting to do some custom drawing to "label" the data points. In order to do this I need the x and y of each data point. How do I access this information?

var draw = Chart.controllers.line.prototype.draw;
Chart.controllers.line = Chart.controllers.line.extend({
    draw: function() {
        draw.call(this, arguments[0]);

        var ctx = this.chart.chart.ctx;
        var points = // how do I get the data points positions?
        $.each (points, function (k, v)
        {
            ctx.beginPath();
            ctx.moveTo(v.x, v.y);
            ctx.lineWidth = 3;
            ctx.strokeStyle = '#ff0000';
            ctx.lineTo(0, v.y);
            ctx.stroke();
         });
    }
});
support

Most helpful comment

You can use the following code. chart is the chart you have created (replace with this if calling from inside chart). Replace n with the dataset that you want and replace i with the point that you want. Both are zero-based indexes.

var meta = chart.getDatasetMeta(n);
var x = meta.data[i]._model.x;
var y = meta.data[i]._model.y;

All 7 comments

@RedHatter on the point objects: _model.x and _model.y are probably what you need

I'm sorry if this is a stupid question, but where is the _model object? I don't see it anywhere in this.chart.

@RedHatter they're on the point objects. Inside of your $.each they would be the 'v'

Ah. The problem is I don't know how to get the point objects. In my current code my $.each doesn't loop over anything.

var points = // how do I get the data points positions?
$.each (points, function (k, v)

oops, I missed that in your sample.

In v2.0.2 it would be this.getDataset()._metaData
In v2.1 (soon to be released) you will need to do:

var points = this.getMeta().data;

You can use the following code. chart is the chart you have created (replace with this if calling from inside chart). Replace n with the dataset that you want and replace i with the point that you want. Both are zero-based indexes.

var meta = chart.getDatasetMeta(n);
var x = meta.data[i]._model.x;
var y = meta.data[i]._model.y;

Here is an example Codepen. Hope it will be helpful.

https://codepen.io/shivabhusal/pen/YxNGQN?editors=0010

Was this page helpful?
0 / 5 - 0 ratings