首页 > 解决方案 > 访问堆积条形图中的嵌套数据

问题描述

我正在尝试更新堆积条的数据选择,如下所示:

.data(series)
   .join('g')
   .attr("fill", d => color(d.key))  
   .selectAll("rect")
     .data(d => d)
     .join("rect") 
     .attr("class", "temp")

下面的代码更新了系列数据中的第一个键,但是如何在不遍历每个键的情况下进行完整更新?必须有一个更优雅的解决方案来访问嵌套数据和更新选择。

         d3.selectAll(".temp")
             .data(series[0], d => d.data.code)  
             .order()
             .attr("x", d => x(d.data.code));

系列数据就像这样 Array {0, 1, data}, {0, 0.5, data} 等

标签: javascriptarraysd3.jsobservable

解决方案


您可以重新运行创建整个堆叠条形图的选择.join:

例如,如果呈现堆叠条的代码是:


 .data(series)
   .join('g')
   .attr("fill", d => color(d.key))  
   .selectAll("rect")
     .data(d => d)
     .join("rect") 
     .attr("class", "temp")
     .attr("x", d => x(d.data.code))
     .attr("y", ...)
     .attr("height", ...)
   ...


要更改图表的数据,您需要做的就是使用不同的series重新运行相同的代码。实现此目的的一种方法是将代码放在接受系列的函数中,并在有新系列要渲染时再次调用它:

function renderChart(series) {

 ...
   .data(series)
   .join('g')
   .attr("fill", d => color(d.key))  
   .selectAll("rect")
     .data(d => d)
     .join("rect") 
     .attr("class", "temp")
     .attr("x", d => x(d.data.code))
     .attr("y", ...)
     .attr("height", ...)
 ...

}

// To render the first series:
renderChart(series1)

// After some time or interaction, render the second series:
renderChart(series2)


推荐阅读