2012-02-21 11 views
0

私はflotを使って棒グラフを生成しています。 は、ここに私のコードbar graph code私はy軸の目盛りが消えるようにする必要がありflotでy軸のダニを取り除く方法

  1. です。
  2. 私はそれを行うにはどのように各バー

の上にいくつかのラベルを配置する必要がありますか?

答えて

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

こんにちはGregさん、Text over the Barの方に感謝しますが、y軸を外した後のデモで、最初のバーが一番上になります。私のテキストはそこに表示されません。 –

+1

@Coder_sLaY私の編集を参照して、私はあなたのためにそれを働いた。 jsFiddleリンクも更新されました。 – GregL

+0

あなたを愛しています。あなたは最高です:) –

関連する問題