亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號