Flot Data Labels on Horizontal Bar Chart

你说的曾经没有我的故事 提交于 2019-12-01 11:52:36

问题


Too much code to paste here so....

Please see JS Fiddle at http://jsfiddle.net/1a2s35m2/ for current code.

I am attempting to create a horizontal bar chart using flot. As you will see from the Fiddle, this works fine but I want to display the values of the bars within the bars themselves and not as labels in the Y Axis, as in the picture below...

I have attempted to use the "labels" plugin and also the barnumbers plugin but these don't seem to work. (Barnumbers comes close but displays 0 1 2 3 as the values.

Any ideas?


回答1:


I'm really starting to sound like a broken record on here, but as your charts become really complicated forget the plugins and do it yourself.

Here's modified code from my links above catered for how you drew your plots:

    // after initial plot draw, then loop the data, add the labels
    // I'm drawing these directly on the canvas, NO HTML DIVS!
    // code is un-necessarily verbose for demonstration purposes
    var ctx = somePlot.getCanvas().getContext("2d"); // get the context
    var allSeries = somePlot.getData();  // get your series data
    var xaxis = somePlot.getXAxes()[0]; // xAxis
    var yaxis = somePlot.getYAxes()[0]; // yAxis
    var offset = somePlot.getPlotOffset(); // plots offset
    ctx.font = "12px 'Segoe UI'"; // set a pretty label font
    ctx.fillStyle = "black";
    for (var i = 0; i < allSeries.length; i++){
        var series = allSeries[i];        
        var dataPoint = series.datapoints.points; // one point per series
        var x = dataPoint[0];
        var y = dataPoint[1];  
        var text = x + '%';
        var metrics = ctx.measureText(text);        
        var xPos = xaxis.p2c(x)+offset.left - metrics.width; // place at end of bar
        var yPos = yaxis.p2c(y) + offset.top - 2;
        ctx.fillText(text, xPos, yPos);
    }

Updated fiddle.



来源:https://stackoverflow.com/questions/26976161/flot-data-labels-on-horizontal-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!