D3 JS绘制条形图

时间:2014-06-16 11:31:34

标签: javascript d3.js charts

我正在尝试使用D3在JS中绘制一些条形图。所以我到目前为止所做的是:

var svg = d3.select("body").append("svg").attr("width", 500).attr("height", 200);
svg.selectAll("rect").... //drawing the bars
svg.selectAll("text").... //putting labels on top of bars

但是当我试图放置标签时,我需要它们位于条形图的中间位置。但要知道把它们放在哪里,我需要以某种方式为条形图引用那些d3对象......我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

看看:

每个都展示了如何定位标签。

例如,在每个水平条的末尾......

  // Create text values that go at end of each bar...
  canvas.selectAll("text")
    .data(dataSet) // Bind dataSet to text elements
    .enter().append("svg:text") // Append text elements
      .attr("x", x)
      .attr("y", function(d, i) { return y(i); })
      //.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
      .attr("dx", function(d) { return x(d.magnitude) - 5; })
      .attr("dy", barHeight-5) // vertical-align: middle
      .attr("text-anchor", "end") // text-align: right
      .text(function(d) { return d.magnitude;})
      .attr("fill", "White");

或每个垂直条顶部的文字......

  // Create text values that go at top of each bar...
  canvas.selectAll("text")
    .data(dataSet) // Instruct to bind dataSet to text elements
    .enter().append("svg:text") // Append text elements
  // Identify root coordinate (x,y)
      //.attr("x", function(d, i) { return x(i) + barWidth; }) // <-- Can't use because of bug in FireFox
      .attr("x", function(d, i) { return x(i) + barWidth / 2; }) // <-- Using because of bug in Firefox
  // Note: the following "+1" offset places value above bar in
  // Space between the top of the bar and the top of the canvas.
  .attr("y", function(d) {
    return canvasHeight - y(d.magnitude ); })
      //.attr("dx", -barWidth/2) // <-------------- Can't use because of bug in FireFox
      .attr("dy", "1em") // Controls padding to place text above bars
      .attr("text-anchor", "middle")
      .text(function(d) { return d.magnitude;})
      .attr("fill", "Black");

我希望这会有所帮助。

答案 1 :(得分:1)

如果您使用xScale作为svg,则可以使用此属性放置文字:

.attr("x", function(d, i) { return xScale(i) + xScale.rangeBand() / 2; })

如果xScale设置为:

var xScale = d3.scale.ordinal()
    .domain(d3.range(dataset.length))
    .rangeRoundBands([0, w], 0.05); 

其中缩放中的w是svg文档的宽度

相关问题