我正在使用 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)
慕尼黑8549860
相关分类