How to set global/specific properies when updating line-chart using Chart.js?

78 views Asked by At

this is my situation http://jsfiddle.net/co3L0bdb/4/

thanks to @potatopeelings help i am now able to set the property highlightFill to all my datasets and this works even when I show/hide a series in the graph. I added:

currentChart.datasets[0].points[8].highlightStroke = "rgba(220,0,0,1)";
currentChart.datasets[1].points[8].highlightStroke = "rgba(0,255,0,1)";
currentChart.datasets[2].points[8].highlightStroke = "rgba(0,0,255,1)";

but what i get, but i do not want, is that when I hide a series, after 2 iteration it starts to plot the hidden data and stops to remove the firsts data of the series. How can I set even series-spefic properties, such as highlightStroke, without the described side effect?

2

There are 2 answers

1
potatopeelings On BEST ANSWER

Instead of setting the dataset property to an empty object, just don't include it in the dataset at all. So

data = {
    labels: chartlabel,
    datasets: [SP, NC, SPA]
};

becomes

data = {
    labels: chartlabel,
    datasets: []
};

if (SP.label !== undefined) data.datasets.push(SP)
if (NC.label !== undefined) data.datasets.push(NC)
if (SPA.label !== undefined) data.datasets.push(SPA)

in 2 places


Replace the data insertion, point attribute setting by a loop (instead of hardcoding it for 3 datasets). So

setInterval(function() {
    currentChart.addData([randomScalingFactor(), randomScalingFactor(), randomScalingFactor()], ++latestLabel);
currentChart.datasets[0].points[8].highlightStroke = "rgba(220,0,0,1)";
currentChart.datasets[1].points[8].highlightStroke = "rgba(0,255,0,1)";
currentChart.datasets[2].points[8].highlightStroke = "rgba(0,0,255,1)";

becomes

var d = []
currentChart.datasets.forEach(function(e) {
    d.push(randomScalingFactor())
})
currentChart.addData(d, ++latestLabel);
currentChart.datasets.forEach(function(dataset) {
    dataset.points[8].highlightStroke = dataset.points[0].highlightStroke;
})

The highlightStroke for the new point is copied from the highlightStroke for the first point of the same series.


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

3
Sabba On
currentChart2.datasets.forEach(function(e) {
    e.points[e.points.length - 1].highlightFill=e.points[0].highlightFill;
    e.points[e.points.length - 1].highlightStroke=e.points[0].highlightStroke;
});

Solves the problem too. http://jsfiddle.net/co3L0bdb/5/