D3在矩形内定位x轴标签并旋转90度

时间:2017-05-10 21:38:35

标签: javascript d3.js svg

我使用D3创建基本条形图

对于我的x轴,我想将每个标签放在各自的条形图上方。文本也应旋转90度

要查看执行此操作的代码,请从第51行开始。https://codepen.io/Fallenstedt/pen/xdYooE

//This is where I attempt to create an x Axis label
//create a container to hold the text element
var textContainer = svg.append('g')
  .selectAll('g')
  .data(data).enter()
  .append('g')
  .attr('class', 'x-axis')
  .attr('x', function(d, i) {
    return i * (width/data.length)
  })
  .attr('y', function(d, i) {
    return height - (d.value) + 15;
  })
  .attr("transform", function(d, i) {return "translate(" + (i * (width/data.length)) + ",330)";});


//now that a container is made, I can append a text element to it so I can rotate the text 90 degrees.
textContainer.append('text')
  .text(function(d) {
    return d.type
  })
  .attr('font-size', '34px')
  .attr('fill', 'white')
  .attr("text-anchor","end")
  .attr("transform", function(d, i) {return "translate(40,0) rotate(-90,0,0)";});

标签出现并旋转90度,但我无法将它们定位在各自的矩形上方。如何将每个x轴标签定位在其矩形正上方?我觉得我的方法过于复杂。

1 个答案:

答案 0 :(得分:1)

您可以在同一容器中创建recttext元素,例如

var rContainer = svg
  .selectAll(".bar")
  .data(data)
  .enter()
  .append("g");

//append rectangles for the bar chart
rContainer
  .append("rect")
  .attr("class", "bar")
  .style("fill", function(d, i) { return color(i); })
  .attr("x", function(d) { return x(d.type); })
  .attr("y", 0)
  .attr("width", x.bandwidth())
  .attr("height", 0)
  .transition()
  .duration(500) //length of animation
  .delay(function(d, i) { return i * 100; }) //delay must be less than duration
  .attr("y", function(d) { return y(d.value); })
  .attr("height", function(d) { return height - y(d.value); });

//append a text element to it so I can rotate the text 270 degrees.
rContainer
  .append("text")
  .text(function(d) { return d.type; })
  .attr("width", x.bandwidth())
  .attr("font-size", "34px")
  .attr("fill", "white")
  .attr("text-anchor", "start")
  .attr("transform", function(d, i) {
    // http://stackoverflow.com/questions/11252753/rotate-x-axis-text-in-d3
    var yVal = y(d.value) - 6;
    var xVal = x(d.type) + x.bandwidth() / 1.6;
    return "translate(" + xVal + "," + yVal + ") rotate(270)";
  });

您可以查看working demo // starts in line 40