freeCodeCamp刷题之用D3实现数据可视化

本文详细介绍了D3.js库在数据可视化中的应用,展示了如何使用D3.js添加、更新和操作DOM元素以显示数据。内容包括动态添加数据、根据数据改变元素样式、设置元素高度、坐标定位、添加悬停效果、创建线性比例尺以及绘制散点图和坐标轴等。这些示例涵盖了D3.js的核心功能,帮助理解如何利用数据驱动的可视化技术创建交互式图表。
摘要由CSDN通过智能技术生成
D3js

此为D3jsAPI文档链接
D3js 是一个可以基于数据来操作文档的 JavaScript 库。可以帮助你使用 HTML, CSS, SVG 以及 Canvas 来展示数据。D3 遵循现有的 Web 标准,可以不需要其他任何框架独立运行在现代浏览器中,它结合强大的可视化组件来驱动 DOM 操作。

append数据

enter() 方法发现页面中没有 h2 元素,但是需要推入数据(每个对应 dataset 中的一个数据)。 新的 h2元素被append到 body,文本为 New item。

<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
    d3.select("body").selectAll("h2")
      .data(dataset)
      .enter()
      .append("h2")
      .text("New item");
  </script>
</body>
使用 D3 中的动态数据
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
    d3.select("body").selectAll("h2")
      .data(dataset)
      .enter()
      .append("h2")
      .text("New Title");
  </script>
</body>
根据数据更改样式
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
    d3.select("body").selectAll("h2")
      .data(dataset)
      .enter()
      .append("h2")
      .text((d) => (d + " USD"))
      .style("color", (d) => {
        if(d<20){
          return 'red';
        }else{
          return 'green';
        }
      });
  </script>
</body>
添加 Class
  • 语法:.attr(‘class’,‘className’)
  • D3 中的 attr() 方法可以给元素添加任何 HTML 属性,包括 class 名称。
动态更新元素高度

语法:.style(“cssProperty”, (d) => d)

<style>
  .bar {
    width: 25px;
    height: 100px;
    display: inline-block;
    background-color: blue;
  }
</style>
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
    d3.select("body").selectAll("div")
      .data(dataset)
      .enter()
      .append("div")
      .attr("class", "bar")
      .style("height", (d) => d)
  </script>
</body>
动态设置每个 Bar 的坐标
<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) => {
          return i*30;
       })
       .attr("y", 0)
       .attr("width", 25)
       .attr("height", 100);
  </script>
</body>
给 D3 标签添加样式通过

D3 可以将样式添加到条形标签中。 fill 属性为 text 节点设置文本颜色, style() 方法设置其它样式的 CSS 规则,例如 font-family 或 font-size。

.attr("fill","red")
.style("font-size","25px")
给 D3 元素添加悬停效果
<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) => 3 * d)
       .attr("fill", "navy")
       .attr("class", "bar")

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

  </script>
</body>
给circle元素添加cx、cy、r属性
<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")
       .attr("cx",(d)=>d[0])
       .attr("cy",(d)=>h-d[1]) // h-d[1]为正向显示
       .attr("r",5)

  </script>
</body>
向散点图的 Circles 添加标签
 svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", (d, i) => d[0]+5)
    .attr("y", (d, i) => d[1])
    .text((d) => (d[0] + ", " + d[1]))
创建线型比例

假设你有一个 100x500 大小的 SVG 画布,你想为许多国家绘制国内生产总值(GDP)的图表。 这组数据将在十亿美元或万亿美元的范围内。 你给 D3 提供一种缩放方法,告诉它如何将大的 GDP 值放置在 100x500 大小的区域。
语法:

 const scale = d3.scaleLinear(); // 在这里创建轴
 const output = scale(50); // 调用 scale,传入一个参数

按比例设置域和范围:

scale.domain([50, 480]); //数据集的域
scale.range([10, 500]);  //数据的范围
使用 d3.max 和 d3.min 函数在数据集中查找最小值和最大值
const exampleData = [34, 234, 73, 90, 6, 52];
d3.min(exampleData)
d3.max(exampleData)

// 如何找到二维数组的最大值和最小值
const locationData = [[1, 7],[6, 3],[8, 3]];
const minX = d3.min(locationData, (d) => d[0]);
添加坐标轴到视图中

另一种改进散点图的方法是添加 x 轴和 y 轴。D3 有两种方法来渲染 y 轴和 x 轴,分别是 axisLeft() 和 axisBottom()。

 const xAxis = d3.axisBottom(xScale);
 const yAxis = d3.axisLeft(yScale);

效果图
在这里插入图片描述

<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 padding = 60;

    const xScale = d3.scaleLinear()
                     .domain([0, d3.max(dataset, (d) => d[0])])
                     .range([padding, w - padding]);

    const yScale = d3.scaleLinear()
                     .domain([0, d3.max(dataset, (d) => d[1])])
                     .range([h - padding, padding]);

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

    svg.selectAll("circle")
       .data(dataset)
       .enter()
       .append("circle")
       .attr("cx", (d) => xScale(d[0]))
       .attr("cy",(d) => yScale(d[1]))
       .attr("r", (d) => 5);

    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text((d) =>  (d[0] + "," + d[1]))
       .attr("x", (d) => xScale(d[0] + 10))
       .attr("y", (d) => yScale(d[1]))

    const xAxis = d3.axisBottom(xScale);
    const yAxis = d3.axisLeft(yScale);


svg.append("g")
   .attr("transform", "translate(0, " + (h - padding) + ")")
   .call(xAxis);
svg.append("g")
   .attr("transform", "translate(" + padding + ",0)")
   .call(yAxis);

  </script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茶茶呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值