Flot - Displays labels on top of stacked bars.

I am using the code snippet from https://stackoverflow.com/a/3/2/11 to mark my fleet data points. So far it has served me well, but now I have to indicate the general values ​​of the stacked bars. There are two series of data, and so far I have been able to calculate the amounts, but I can not find the correct location for my labels. I would like to place them on top of the stacks, but pointOffset gives me offsets based on non-stationary bars.

This is the code that I am currently using, it puts labels where the data points of the second series will be, if the bars have not been stacked, which puts them somewhere in the upper bars.

$.each(p.getData()[1].data, function(i, el){ var series0 = p.getData()[0].data; sum = el[1] + series0[i][2] var o = p.pointOffset({x: el[0], y: el[1]}); $('<div class="data-point-label">' + sum + '</div>').css( { position: 'absolute', left: o.left - 5, top: o.top , display: 'none' }).appendTo(p.getPlaceholder()).fadeIn('slow'); }); 

Edit # 1: While I was trying to use c2p / p2c, calculating the upper value, using the upper values ​​of single data points and finding additional documentation on the stack plugin. I'm afraid none of this helped me.

Edit # 2: I also tried the code specified in https://stackoverflow.com/a/147286/..but this does not work for me. I suspect the author is using a plugin with some shortcuts ...

+4
source share
1 answer

The solution to put labels at the top of the columns in the usinjg canvas stack is that you need to calculate xPoint in the base of the sum of the values ​​in the full stack.

Here is a sample code

 var sumaArr = []; for (var u = 0; u < p.getData().length; u++) { $.each(p.getData()[u].data, function (i, el) { sumaArr[i] > 0 ? sumaArr[i] = sumaArr[i] + el[1] : sumaArr[i] = el[1]; }); } var ctx = p.getCanvas().getContext("2d"); var data = p.getData()[p.getData().length - 1].data; var xaxis = p.getXAxes()[0]; var yaxis = p.getYAxes()[0]; var offset = p.getPlotOffset(); ctx.font = "12px 'Segoe UI'"; ctx.fillStyle = "gray"; for (var i = 0; i < data.length; i++) { var text = sumaArr[i]; var metrics = ctx.measureText(text); var xPos = (xaxis.p2c(data[i][0]) + offset.left) - metrics.width / 2; var yPos = yaxis.p2c(sumaArr[i]) + offset.top - 5; ctx.fillText(text, xPos, yPos); } 

Var yPos uses the sum of the values ​​that make up the full stack.

0
source

Source: https://habr.com/ru/post/1434284/


All Articles