我正在使用 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)
如何在D3.js中指定樹的最后一個元素的標簽名稱?
慕婉清6462132
2023-07-06 10:09:53