I am encountering a problem, how to update the plotlines(on YAxis) dynamically? Specifically, I need to calculate a max, min and average value for a period of the chart, then setup the 3 lines which they stand for. How can I do that? many thanks!
0
votes
1 Answers
1
votes
This is a very simple example of how to update plotlines dynamically.
- It has one data series which can be updated by the press of a button.
- When pressing the second button, plotlines will be added or removed+redrawn according to the data of the series.
- If you want to use a subset of data points, feel free to work on the function
getKPIByDataaccordingly, or change thedataargument.
http://jsfiddle.net/hsL4pwsh/12/
;$(function() {
var curActiveData = 1;
var addedPlotlines = false;
var data1 = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];
var data2 = [31.9, 73.5, 117.4, 29.2, 109.0, 181.0, 212.6, 137.5, 225.4, 199.1, 91.6, 11.4];
var getKPIByData = function(data) {
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
function getMinOfArray(numArray) {
return Math.min.apply(null, numArray);
}
var minRate,
maxRate = 0,
rate,
i,
avgRate,
totalRate = 0;
for (i = 0; i < data.length; i++) {
totalRate += data[i];
}
return {
minRate: getMinOfArray(data),
maxRate: getMaxOfArray(data),
avgRate: totalRate / data.length
};
};
$('#container').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
},
series: [{
data: data1
}]
});
// the button action
var $button1 = $('#addPlotlines'),
$button2 = $('#updatePlotlines'),
chart = $('#container').highcharts();
$button1.on("click", function() {
var curData = [];
for (var i = 0; i < chart.series[0].data.length; i++) {
curData[curData.length] = chart.series[0].data[i].y;
}
var result = getKPIByData(curData);
if (addedPlotlines) {
chart.yAxis[0].removePlotLine('min');
chart.yAxis[0].removePlotLine('max');
chart.yAxis[0].removePlotLine('avg');
}
chart.yAxis[0].addPlotLine({
color: 'green',
width: 2,
id: "min",
value: result.minRate
});
chart.yAxis[0].addPlotLine({
color: 'red',
width: 2,
id: "max",
value: result.maxRate
});
chart.yAxis[0].addPlotLine({
color: 'blue',
width: 2,
id: "avg",
value: result.avgRate
});
addedPlotlines = true;
});
$button2.on("click", function() {
var newActive = (curActiveData == 1) ? 2 : 1;
console.log(newActive);
chart.series[0].update({
data: (newActive == 1) ? data1 : data2
});
curActiveData = newActive;
});
});