2014-02-11 106 views
12

是否有可能將值標籤放在條上,以便它們位於它們的中心位置?JQuery,Flot,valuelabels,center

如果我設置了條形碼align: "center",條上的標籤關閉而不居中。

enter image description here

<script type="text/javascript"> 

    $(function() { 

     var data = [<?php echo $data; ?>]; 

     $.plot("#<?php echo $target; ?> .chart-placeholder", data, { 
      series: { 
       color: "rgb(57,137,209)", 
       bars: { 
        show: true, 
        // align: "center", 
        barWidth: .8, 
        fill: 1  
       }, 
       valueLabels: { 
        show: true, 
        showAsHtml: true, 
        align: "center" 
       }    
      }, 
      grid: { 
       aboveData: true, 
       hoverable: true, 
       borderWidth: 0 
      }, 
      xaxis: { 
       mode: "categories", 
       tickLength: 0, 
       labelAngle: -45, 
       showAsHtml: true 
      }, 
      yaxis: { 
       show: false, 
       tickLength: 0 
      }, 
     }); 
    }); 

    </script> 

Flot

Flot Value Labels plugin

JSFIDDLE

+0

你能爲你的問題得到[小提琴](http://jsfiddle.net)? – Raidri

+0

@Raidri - 完成! – Philip

回答

13

插件讓你失望?只要自己做,生活就那麼簡單了。這是flot優勢,緊湊的代碼,得到的你的出路......

以下是我想補充這些標籤:

// draw initial plot 
// notice no categories plugin either, why? 
// Because it's easier to do it yourself... 
var series = {data: [[0, 5.2], [1, 3], [2, 9.2], [3, 10]], 
       lines: {show: false}, 
       bars: {show: true, barWidth: 0.75, align:'center'}} 
var somePlot = $.plot("#placeholder", [ series ], { 
    xaxis: { 
     ticks: [[0,"One"],[1,"Two"], 
       [2,"Three"],[3,"Four"]] 
    } 
}); 

// 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 data = somePlot.getData()[0].data; // get your series data 
var xaxis = somePlot.getXAxes()[0]; // xAxis 
var yaxis = somePlot.getYAxes()[0]; // yAxis 
var offset = somePlot.getPlotOffset(); // plots offset 
ctx.font = "16px 'Segoe UI'"; // set a pretty label font 
ctx.fillStyle = "black"; 
for (var i = 0; i < data.length; i++){ 
    var text = data[i][1] + ''; 
    var metrics = ctx.measureText(text); 
    var xPos = (xaxis.p2c(data[i][0])+offset.left) - metrics.width/2; // place it in the middle of the bar 
    var yPos = yaxis.p2c(data[i][1]) + offset.top - 5; // place at top of bar, slightly up 
    ctx.fillText(text, xPos, yPos); 
} 

小提琴示範是here

產地:

enter image description here

+0

唯一的,最好的,謝謝! – Philip

3

有似乎是默認值標籤插件無解。 但有一些開放的issues討論這個和here是一些你可以嘗試的建議解決方案。

This version來自neoDD69的插件在標籤居中方面做得更好,正如你可以在這個小提琴中看到的(見下面的評論)。

+0

[小提琴鏈接](http://jsfiddle.net/GZQzb/) – Raidri