在水平条形图上绘制数据标签

时间:2014-11-17 15:34:21

标签: javascript jquery flot

Too much code to paste here so....

请在http://jsfiddle.net/1a2s35m2/查看JS Fiddle获取最新代码。

我正在尝试使用flot创建一个水平条形图。正如您将从小提琴中看到的,这可以正常工作,但我想在条形图中显示条形的值而不是Y轴中的标签,如下图所示...... enter image description here

我试图使用"标签"插件和barnumbers插件,但这些似乎不起作用。 (Barnumbers接近但显示0 1 2 3作为值。

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

我在这里真的开始听起来像broken record,但是当你的图表变得非常复杂时,请忘记插件并亲自动手。

以上链接中修改过的代码可以照亮您的绘图方式:

    // 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);
    }

更新了fiddle

相关问题