数据可视化|d3的基本操作

发布于:2024-10-09 ⋅ 阅读:(82) ⋅ 点赞:(0)

select和text()

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3.js Bar Chart</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
    </ul>
    <script>
        d3.select("body").append("h1").text("Learning D3")
        d3.select("ul").append("li").text("3")
      </script>
</body>
</html>

data、enter、append

调用selectAll会得到相应标签组成的集合
如果已经有了,比如有一个li,那它的text不会变。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3.js Bar Chart</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <ul>
        <li>d</li>
    </ul>
  <script>
    const dataset = ["a", "b", "c"];
    d3.select("ul").selectAll("li")
      .data(dataset)
      .enter()
      .append("li")
      .text(d=>d);
  </script>
</body>
</html>

.style(“font-family”,“verdana”)

.style("font-family","verdana")

回调

.style("color",d=>{
        return d<20?"red":"green"
      })

attr(“class”,“bar”)

添加类属性

.style(“height”,d=>${d}px)

动态设置高度

.append(“rect”) // 先追加 rect 元素

<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)
                  // 添加矩形
                  .append("rect") // 先追加 rect 元素
                  .attr("width", 25) // 设置宽度
                  .attr("height", 100) // 设置高度
                  .attr("x", 0) // 设置 x 坐标
                  .attr("y", 0) // 设置 y 坐标
                  .attr("fill", "blue"); // 可选:设置填充颜色
  </script>
</body>


网站公告

今日签到

点亮在社区的每一天
去签到