簡體   English   中英

如何將2d數據輸入d3並訪問每個子數組的句柄以操縱其元素?

[英]how to enter 2d data into d3 and access the handle of each subarray to manipulate its elements?

說,我有2d arr = [[1,2,3],[100,200],['A','B'...'Z']] 如您所見, arr[0].length!=arr[1].length!=arr[2].length

我想將它們表示為svg中的文本標簽。

此外,我想保持靈活性,例如每個子數組從(x,y)開始,以及子數組每個元素(x,y)之間的間隔有多寬。

d3.select('svg').selectAll('g').data(arr).enter().append('g').selectAll('text').data((d)=>d).enter().append('text').text(d=>d)

但是這樣一來,我就失去了每克內的信息。 我嘗試在.selectAll('text')之前設置.attr('x',(d,i)=>(i + 1)* 20),但是它只會將'x'-attr添加到g上並且沒有效果在頁面上顯示的文本(即數組的元素)上。

問題是我將所有這些都放入了DOM中。 但是,如何像行一樣,在一組中(沒有硬編碼)調整它們的.attr('x')、. attr('y'),但是每行在元素之間可以有自己的間距?

您可以嘗試使用“ getBBox”或getBoundingClientRect來獲取節點寬度,然后進行水平布局。

 var arr = [[1,2,3],[100,200],['A','B', 'C', 'D', 'E', 'Z']] var container = d3.select("#box") .append("g") .attr("transform", "translate(10, 50)"); container .selectAll("text") .data(arr) .enter() .append("text") .text(d => d); /* Using "getBBox" or "getBoundingClientRect" method to get each text node's width, then move them one another. You must make sure the svg element and its parent elements are visible, which means "display: none" is should not applied on them. */ var xInit = 0, padding = 15; container .selectAll("text") .each(function (d, i) { d3.select(this).attr("x", xInit); xInit += this.getBBox().width + padding; }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script> <svg id="box" width="500" height="300"></svg> 

我想我明白了。 不確定這是否是明確的解決方案,但它是否有效。 首先,在創建g s之后添加id。 然后根據id(即行)為x和y坐標編寫函數。

function x(d,i,j){
  let node_id = j[0].parentNode.id; // allows to dynamically access the ids of every text element
  //calculate x_value here
  return x_value;
}

該功能可以傳遞到原始鏈中。

d3.select('svg').selectAll('g').data(arr).enter().append('g')
    .attr('id', (d,i)=>i) // adding ids to every g based on the array index
    .selectAll('text').data((d)=>d).enter().append('text').text(d=>d)
    .attr('x', x) // here

如果有人知道更精簡的解決方案,那將不勝感激,因為我是Java和d3的新手。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM