D3 编码顺序

D3 Coding Order

本文关键字:顺序 编码 D3      更新时间:2023-09-26

我不清楚必须编写 D3 代码的模式。

例如,在下面的代码片段中,如果我在创建 svg 元素后提到代码的第 3 部分(图表标题),我的图表不会显示标题文本,但如果我在创建 svg 之前提到第 3 部分,它只是工作。

为什么?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
<style>
    circle.dimple-series-1{
    fill: red;
    }    
    h2{
    color: black;
    text-align: center;
    font-family: monospace;
    font-size: 20px;
    }   
    </style>
  <script src="http://d3js.org/d3.v3.min.js"></script>
  <script src="http://dimplejs.org/dist/dimple.v2.0.0.min.js"></script>
    <script type="text/javascript">
      function draw(data) {
      /*
        D3.js setup code
      */
          "use strict";
          var margin = 75,
              width = 1400 - margin,
              height = 600 - margin;
          /*TITLE*/
          d3.select("body")
          .append("h2").text("Goals by Year!");
          /*Creating SVG*/
          var svg = d3.select("body")
            .append("svg")
              .attr("width", width + margin)
              .attr("height", height + margin)
            .append('g')
            .attr('class','chart');
      /*
        Dimple.js Chart construction code
      */
          var myChart = new dimple.chart(svg, data);
          var x = myChart.addTimeAxis("x", "year"); 
          x.dateParseFormat="%Y"
          x.tickFormat="%Y";
          x.timeInterval= 4;
          myChart.addMeasureAxis("y", "attendance");
          myChart.addSeries(null, dimple.plot.line);
          myChart.addSeries(null, dimple.plot.scatter);

          myChart.draw();
        };
      </script>
  </head>
<body>
  <script type="text/javascript">
  /*
    Use D3 (not dimple.js) to load the TSV file
    and pass the contents of it to the draw function
    */
  d3.tsv("world_cup.tsv", draw);
  </script>
</body>
</html>

您的标题不会添加到 svg 中。您正在将标题对象追加到正文。 我认为一旦您添加了 SVG,它就不会出现的唯一原因是因为它是在 DOM 中添加到它之后的,所以可能看不见? 这取决于您的 CSS,但我相当确定该元素仍然会被添加。

在第一种情况下,您的 DOM 将如下所示:

<body>
    <h2>Goals by Year!</h2>
    <svg>
       <... Dimple Stuff ...>
    </svg>
</body>

在第二种情况下,如下所示:

<body>
    <svg>
       <... Dimple Stuff ...>
    </svg>
    <h2>Goals by Year!</h2>
</body>

如果要将标题添加到 SVG 本身,则需要使用 SVG 形状,并且需要定位 SVG 而不是正文。 例如:

var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin)
        .attr("height", height + margin);
svg.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .style("fill", "black")
    .text("Goals by Year!");
... Dimple Stuff

在这种情况下,您的 DOM 将如下所示:

<body>
    <svg>
       <text x=100 y=100 style="fill:black">Goals by Year!</text>
       <... Dimple Stuff ...>
    </svg>
</body>

编辑:删除了注释。 酒窝似乎可以在 svg 中使用组。