2012-02-21 104 views

回答

4

好吧,經過大量的Flot和下載源代碼後,我終於想出了一個很好的起點。

jsFiddle演示是here

代碼的膽量使用鉤其中提請標籤:

function drawSeriesHook(plot, canvascontext, series) { 
    var ctx = canvascontext, 
     plotOffset = plot.offset(), 
     labelText = 'TEST', // customise this text, maybe to series.label 
     points = series.datapoints.points, 
     ps = series.datapoints.pointsize, 
     xaxis = series.xaxis, 
     yaxis = series.yaxis, 
     textWidth, textHeight, textX, textY; 
    // only draw label for top yellow series 
    if (series.label === 'baz') { 
     ctx.save(); 
     ctx.translate(plotOffset.left, plotOffset.top); 

     ctx.lineWidth = series.bars.lineWidth; 
     ctx.fillStyle = '#000'; // customise the colour here 
     for (var i = 0; i < points.length; i += ps) { 
      if (points[i] == null) continue; 

      textWidth = ctx.measureText(labelText).width; // measure how wide the label will be 
      textHeight = parseInt(ctx.font); // extract the font size from the context.font string 
      textX = xaxis.p2c(points[i] + series.bars.barWidth/2) - textWidth/2; 
      textY = yaxis.p2c(points[i + 1]) - textHeight/2; 
      ctx.fillText(labelText, textX, textY); // draw the label 
     } 
     ctx.restore(); 
    } 
} 

見,你可以自定義標籤的意見。

要刪除Y軸刻度,這只是一個簡單的選項設置。另外,您可以計算每個條形碼堆棧的最大y值,然後添加大約100,以設置允許標籤佔用空間的最大Y值。所有這些代碼然後變成:

// determine the max y value from the given data and add a bit to allow for the text 
var maxYValue = 0; 
var sums = []; 
$.each(data,function(i,e) { 
    $.each(this.data, function(i,e) { 
     if (!sums[i]) { 
      sums[i]=0; 
     }   
     sums[i] += this[1]; // y-value 
    }); 
}); 
$.each(sums, function() { 
    maxYValue = Math.max(maxYValue, this); 
}); 
maxYValue += 100; // to allow for the text 


var plot = $.plot($("#placeholder"), data, { 
    series: { 
     stack: 1, 
     bars: { 
      show: true, 
      barWidth: 0.6, 
     }, 
     yaxis: { 
      min: 0, 

      tickLength: 0 
     } 
    }, 
    yaxis: { 
     max: maxYValue, // set a manual maximum to allow for labels 
     ticks: 0 // this line removes the y ticks 
    }, 
    hooks: { 
     drawSeries: [drawSeriesHook] 
    } 
}); 

這應該讓你開始。我敢肯定,你可以從這裏拿走它。

+0

嗨格雷格感謝文本的酒吧,但在演示後刪除y軸第一個酒吧去最頂部..所以我的文字不可見那裏...有沒有解決方案呢? – 2012-02-21 13:32:55

+1

@Coder_sLaY看到我的編輯,我甚至爲你工作。 jsFiddle鏈接也被更新了。 – GregL 2012-02-21 13:59:21

+0

愛你格雷格。你是最棒的:) – 2012-02-21 14:00:15