我对d3.js和javascript很陌生. 我只是想try 一些d3示例代码.

我从here复制了d3.js代码.

<!DOCTYPE html>
<meta charset="utf-8" />
<style>
  .node circle {
    fill: #999;
  }

  .node text {
    font: 10px sans-serif;
  }

  .node--internal circle {
    fill: #555;
  }

  .node--internal text {
    text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
  }

  .link {
    fill: none;
    stroke: rgb(214, 15, 145);
    stroke-opacity: 0.4;
    stroke-width: 1px;
  }

  form {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  }

  label {
    display: block;
  }
</style>
<svg width="928" height="928"></svg>
<script src="http://d3js.org/d3.v6.min.js"></script>
<script>

  const data = {
        name: "Name",
        children: [
          {
            name: "A_F",
            children: [
              {
                name: "Alice",
              },
              {
                name: "Bob",
              },
              {
                name: "Charlie",
              },
            ],
          },
          {
            name: "G_P",
            children: [
              {
                name: "Gary",
              },
              {
                name: "Helen",
              },
            ],
          },
        ],
      };

  // Specify the chart’s dimensions.
  const width = 928;
  const height = width;
  const radius = width / 6;

  // Create the color scale.
  const color = d3.scaleOrdinal(d3.quantize(d3.interpolateRainbow, data.children.length + 1));

  // Compute the layout.
  const hierarchy = d3.hierarchy(data)
      .sum(d => d.value)
      .sort((a, b) => b.value - a.value);
  const root = d3.partition()
      .size([2 * Math.PI, hierarchy.height + 1])
    (hierarchy);
  root.each(d => d.current = d);

  // Create the arc generator.
  const arc = d3.arc()
      .startAngle(d => d.x0)
      .endAngle(d => d.x1)
      .padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005))
      .padRadius(radius * 1.5)
      .innerRadius(d => d.y0 * radius)
      .outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1))

  // Create the SVG container.
  const svg = d3.create("svg")
      .attr("viewBox", [-width / 2, -height / 2, width, width])
      .style("font", "10px sans-serif");

  // Append the arcs.
  const path = svg.append("g")
    .selectAll("path")
    .data(root.descendants().slice(1))
    .join("path")
      .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
      .attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0)
      .attr("pointer-events", d => arcVisible(d.current) ? "auto" : "none")

      .attr("d", d => arc(d.current));

  // Make them clickable if they have children.
  path.filter(d => d.children)
      .style("cursor", "pointer")
      .on("click", clicked);

  const format = d3.format(",d");
  path.append("title")
      .text(d => `${d.ancestors().map(d => d.data.name).reverse().join("/")}\n${format(d.value)}`);

  const label = svg.append("g")
      .attr("pointer-events", "none")
      .attr("text-anchor", "middle")
      .style("user-select", "none")
    .selectAll("text")
    .data(root.descendants().slice(1))
    .join("text")
      .attr("dy", "0.35em")
      .attr("fill-opacity", d => +labelVisible(d.current))
      .attr("transform", d => labelTransform(d.current))
      .text(d => d.data.name);

  const parent = svg.append("circle")
      .datum(root)
      .attr("r", radius)
      .attr("fill", "none")
      .attr("pointer-events", "all")
      .on("click", clicked);

  // Handle zoom on click.
  function clicked(event, p) {
    parent.datum(p.parent || root);

    root.each(d => d.target = {
      x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
      x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
      y0: Math.max(0, d.y0 - p.depth),
      y1: Math.max(0, d.y1 - p.depth)
    });

    const t = svg.transition().duration(750);

    // Transition the data on all arcs, even the ones that aren’t visible,
    // so that if this transition is interrupted, entering arcs will start
    // the next transition from the desired position.
    path.transition(t)
        .tween("data", d => {
          const i = d3.interpolate(d.current, d.target);
          return t => d.current = i(t);
        })
      .filter(function(d) {
        return +this.getAttribute("fill-opacity") || arcVisible(d.target);
      })
        .attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0)
        .attr("pointer-events", d => arcVisible(d.target) ? "auto" : "none") 

        .attrTween("d", d => () => arc(d.current));

    label.filter(function(d) {
        return +this.getAttribute("fill-opacity") || labelVisible(d.target);
      }).transition(t)
        .attr("fill-opacity", d => +labelVisible(d.target))
        .attrTween("transform", d => () => labelTransform(d.current));
  }
  
  function arcVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0;
  }

  function labelVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03;
  }

  function labelTransform(d) {
    const x = (d.x0 + d.x1) / 2 * 180 / Math.PI;
    const y = (d.y0 + d.y1) / 2 * radius;
    return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`;
  }

  svg.node();
</script>

我唯一编辑的是删除最后的return svg.node();并将其更改为svg.node();

当我启动本地http服务器(py3 -m http.server 8000)时,我发现浏览器中没有显示任何内容,并且当我点击inspect时也没有错误.

只是想学习如何分类这个问题和解决问题.谢谢你!

推荐答案

不幸的是,D3规范的示例通常在Observable上找到,虽然它交互性和有用,但如果不做一两次修改,就不能转换为常规的javascript.

首先,Observable使用return svg.node()返回一个分离的DOM元素,以便显示它.分离的 node 是用d3.create()创建的.这在vanilla javascript环境中是行不通的:通常,您可以直接在SVG中附加d3.select("parentElement").append("svg"),或者如果已经存在,则 Select 它,就像代码中的(d3.select("svg")).

但是,您的示例有一种数据格式,其中叶 node (本身没有子 node )有一个value属性:

 "children":[{"name":"AgglomerativeCluster","value":3938},{"name":"CommunityStructure","value":3812}

您的数据不会:

children: [{ name: "Alice", }, { name: "Bob", },

这很重要,因为层次 struct 使用sum函数来列表每个 node 的相对大小:

  const hierarchy = d3.hierarchy(data)
     .sum(d => d.value)

因此,您可以 for each 叶 node 添加一个value属性,这将生成一个视觉.但是,如果每个叶子应该具有相同的权重,那么你可以使用用途:

   const hierarchy = d3.hierarchy(data)
     .count()

其中每个父 node 将根据每个分支中的叶 node 的数量加权.

Javascript相关问答推荐

Express.js:使用Passport.js实现基于角色的身份验证时出现太多重定向问题

如何访问react路由v6加载器函数中的查询参数/搜索参数

react 路由加载程序行为

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

Vue:ref不会创建react 性属性

没有输出到带有chrome.Devtools扩展的控制台

在页面上滚动 timeshift 动垂直滚动条

格式值未保存在redux持久切片中

查找最长的子序列-无法重置数组

无法从NextJS组件传递函数作为参数'

如何创建返回不带`new`关键字的实例的类

如何在Svelte中从一个codec函数中调用error()?

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

如何在我的Next.js项目中.blob()我的图像文件?

如何为仅有数据可用的点显示X轴标签?

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

JavaScript -复制到剪贴板在Windows计算机上无效

TypeORM QueryBuilder限制联接到一条记录

我如何才能获得价值观察家&对象&S的价值?

将匿名函数附加到链接的onClick属性