给 D3 元素添加工具提示 & 使用 SVG Circles 创建散点图

207 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的22天,点击查看活动详情

给 D3 元素添加工具提示

介绍

当用户在一个对象上悬停时,提示框可以显示关于这个对象更多的信息。 在可视化中有多种方法添加提示框,这个挑战将使用 SVG 的 title 元素。

titletext() 方法一起给每组动态添加数据。

实操

在每个 rect 节点下附加 title 元素。 然后用回调函数调用 text() 方法使它的文本显示数据值。

  1. 你应该有 9 个 title 元素。
  2. 第一个 title 元素的提示框文本应为 12
  3. 第二个 title 元素的提示框文本应为 31
  4. 第三个 title 元素的提示框文本应为 22
  5. 第四个 title 元素的提示框文本应为 17
  6. 第五个 title 元素的提示框文本应为 25
  7. 第六个 title 元素的提示框文本应为 18
  8. 第七个 title 元素的提示框文本应为 29
  9. 第八个 title 元素的提示框文本应为 14
  10. 第九个 title 元素的提示框文本应为 9
<style>
  .bar:hover {
    fill: brown;
  }
</style>
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h);

    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => d * 3)
       .attr("fill", "navy")
       .attr("class", "bar")
       
       .append("title")
       .text(d=>d)

    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text((d) => d)
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - (d * 3 + 3))

  </script>
</body>

使用 SVG Circles 创建散点图

介绍

散点图是另一种形式的可视化。 它用圆圈来映射数据点,每个数据点有两个值。 这两个值和 xy 轴相关联,在可视化中用来给圆圈定位。

SVG 用 circle 标签来创建圆形。 它和之前用来构建条形图的 rect 非常相像。

实操

使用 data()enter()append() 方法将 dataset 和新添加到 SVG 画布上的 circle 元素绑定起来。

注意: 圆形并不可见,因为我们还没有设置它们的属性。 我们会在下一个阶段中设置属性。

  1. 应该有 10 个 circle 元素。
<body>
  <script>
    const dataset = [[ 34,    78 ],
                  [ 109,   280 ],
                  [ 310,   120 ],
                  [ 79,    411 ],
                  [ 420,   220 ],
                  [ 233,   145 ],
                  [ 333,   96 ],
                  [ 222,   333 ],
                  [ 78,    320 ],
                  [ 21,    123 ]
                ];


    const w = 500;
    const h = 500;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h);

    svg.selectAll("circle")

       .data(dataset)
       .enter()
       .append("circle")

  </script>
</body>