【问题标题】:D3 axis label has to be added separately?D3轴标签必须单独添加?
【发布时间】:2017-07-12 07:06:58
【问题描述】:

在使用 D3 v4 的this axis label example 中,它在 svg 下添加了 x 轴和文本标签作为单独的节点。

  // Add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // text label for the x axis
  svg.append("text")             
      .attr("transform",
            "translate(" + (width/2) + " ," + 
                           (height + margin.top + 20) + ")")
      .style("text-anchor", "middle")
      .text("Date");

当我链接上面的代码时(因此将文本元素移动到 x 轴组下):

  // Add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x))
      .append("text")             
      .style("text-anchor", "middle")
      .text("Date");

然后我的轴标题不再可见(见下面的截图)。我仍然可以在 DOM 中的 x 轴组下找到我的文本元素,但它不在呈现的 HTML 中。

我想知道:

  1. D3 是否有意让我分别添加轴及其标签(即不链接)?

  2. 为什么我的文本元素在 x 轴组下移动后不可见?

【问题讨论】:

    标签: javascript d3.js svg data-visualization


    【解决方案1】:

    D3轴标签必须单独添加?

    不,它没有。你可以链接,这不是问题。这里的问题是文本元素的fill

    正如您在链接的屏幕截图中所见,容器组的“无”为fill。由于文本继承了父级的属性/样式,因此您必须将其 fill 从“无”更改为您想要的任何颜色:

    var svg = d3.select("svg");
    
    var xScale = d3.scaleLinear()
        .domain([1, 10])
        .range([10,390]);
    
    var xAxis = d3.axisBottom(xScale);
    
    var gX = svg.append("g")
        .attr('class', 'axis')
        .attr("transform","translate(0,40)")
        .call(xAxis)
        .append("text")
        .attr("fill", "black")//set the fill here
        .attr("transform","translate(120, 40)")
        .text("Hello World!!!");
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <svg width="400" height="80"></svg>

    PS:这个问题在 D3 v3.x 中不会发生。

    【讨论】:

      猜你喜欢
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 2013-07-19
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多