【问题标题】:D3 position x axis label within rectangle and rotate 90 degreesD3在矩形内定位x轴标签并旋转90度
【发布时间】:2017-10-09 17:34:07
【问题描述】:

我正在使用 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 轴标签定位在其矩形的正上方?我觉得我的处理方法过于复杂。

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案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

    【讨论】:

    • 现在更有意义了。我没有考虑使用x.bandwidth() 来翻译每段文字。谢谢!我一定会再讨论一下。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多