vp_arth vp_arth - 6 months ago 34
Javascript Question

Chart.js change vertical position of points

I extend

Chart.types.Line
and override scale to some constant value.

What I need now - to show points with


  • y > scale.max
    at
    scale.max
    position

  • y < scale.min
    at
    scale.min
    position



to ability of user interaction with them.

Titles should be correct(not modified) values, so I can't just modify datasets.

How can I achieve that?

Simplified code:

function ChartFactory(title) {
Chart.types.Line.extend({
name: title,
buildScale: function() {
this.options.scaleOverride = true;
this.options.scaleSteps = 10;
this.options.scaleStepWidth = this.options.S;
this.options.scaleStartValue = this.options.target - 5 * this.options.S;
Chart.types.Line.prototype.buildScale.apply(this, arguments);
},
draw: function () {
var chart = this;
Chart.types.Line.prototype.draw.apply(chart, arguments);
// some additional graphic here
}
});
}

Answer

Just add the following at the end of your buildScale

...
var scale = this.scale;
var originalCalculateY = scale.calculateY;
scale.calculateY = function(y) {
    if (y > scale.max)
        return originalCalculateY.apply(this, [scale.max]);
    else if (y < scale.min)
        return originalCalculateY.apply(this, [scale.min]);
    else
        return originalCalculateY.apply(this, [y]);
}
...

It would a bit confusing because you'd still have the axis labels.


Fiddle - http://jsfiddle.net/wjb3k4gx/

Comments