为了账号安全,请及时绑定邮箱和手机立即绑定

如何在D3.js中指定树的最后一个元素的标签名称?

如何在D3.js中指定树的最后一个元素的标签名称?

慕婉清6462132 2023-07-06 10:09:53
我正在使用 D3.js 并尝试以带有节点的树的形式显示一些数据。这些标签对于根和第一层子层效果很好。但是最后一层子级包含数据,其中每个数据都是单个对象,我想在该对象中显示国家/地区名称。数据最初采用数组的形式,因此我对它们进行过滤以形成在 D3.js 中可视化所需的结构。agroforestry存储用于进行可视化的数据。  const agroforestry = {    name: "Intiative 2020",    children: [      {        name: "Agroforestry",        children: [],      },      {        name: "No Agroforestry",        children: [],      },    ],  };  data.forEach((d) =>    d.agroforestry === 1      ? agroforestry.children[0].children.push(d)      : agroforestry.children[1].children.push(d)  );内部对象示例agroforestry.children[1].children:  const example = {    agroforestry: 0,    avoided_degradation_and_deforestation: 1,    country: "Chile",    descriptions:      "In Chile's Patagonia region, grasslands were severely degraded after years of uncontrolled sheep and cattle grazing",    funding: 0,    geolocation: "(-31.7613365, -71.3187697)",    investment_type: "Private",    latitude: -31.7613365,    locations: "Patagonia",    longitude: -71.3187697,    low_carbon_agriculture: 0,    partner_organization: "[]",    partner_organization_urls: "[]",    reforestation: 0,    silvopasture: 0,    sustainably_managed_grasslands: 1,    titles: "Ecological restoration chacabuco valley",    urls:      "https://initiative20x20.org/restoration-projects/ecological-restoration-chacabuco-valley",  };父级的标签可见,并将.text((node) => node.data.name)其设置为标签。    svg      .selectAll(".label")      .data(root.descendants())      .join("text")      .attr("class", "label")      .text((node) => node.data.name)      .attr("text-anchor", "middle")      .attr("font-size", 14)      .attr("x", (node) => node.y)      .attr("y", (node) => node.x - 10);当我选择 Country 时,父级标签不可见,但国家/地区标签可见(需要编辑样式,但它有效).text((node) => node.data.country)。    svg       .selectAll(".label")       .data(root.descendants())       .join("text")       .attr("class", "label")       .text((node) => node.data.country)       .attr("text-anchor", "middle")       .attr("font-size", 14)       .attr("x", (node) => node.y)
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

有两种互斥的情况:

  • 该节点有子节点吗?=>data.name

  • 否则,该节点是叶节点=>data.country

所以真正的问题是我们如何检查当前节点是(不是)叶节点

为此,我们可以在节点上使用 d3-hierarchy 提供的方法。(也可以查看那里的好例子。)其中一个例子向我们展示了该node.children属性。

如果已设置,则该节点有子节点(因此它不是叶节点),我们可以在自己的代码中像这样使用它:

svg                       // node          // leaf
  .text((node) => node.children ? node.data.name : node.data.country)


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信