javascript 将 D3 与多维数组/对象一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14062609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:37:01  来源:igfitidea点击:

Using D3 with a multi-dimensional array/object

javascriptjsond3.js

提问by NChase

I have a JSON file with a format like the following:

我有一个格式如下的 JSON 文件:

{
   "John":{
      "name":"John",
      "counts":[ 1, 5, 10, 6 ]
   },
   "Steve":{
      "name":"Steve",
      "counts": [ 6, 4, 50, 40 ]
   }
}

I'm trying to do a D3 visualization that does a simple column chart for those counts, with a name label to the left. When I have a single data series and a name I can do it like so:

我正在尝试做一个 D3 可视化,它为这些计数做一个简单的柱状图,左边有一个名称标签。当我有一个数据系列和一个名字时,我可以这样做:

svg.selectAll("rect").data([ 1, 5, 10, 6 ]).enter().append("rect")
            .attr("x",function(d,i) { return i*columnWidth; })
            .attr("y",function(d) { return (rowHeight-scale(d));})
            .attr("width",columnWidth)
            .attr("height",function(d) { return snowScale(d); } );

svg.selectAll("text").data("John").enter().append("text")
        .text(function(d) { return d; })
        .attr("x",nameBuffer)
        .attr("y",function(d,i) { return rowHeight; })              
        .attr("font-size", "14px");

This works for a single row with the data supplied directly, with the text label off to the left and then a series of columns of equal width for each datapoint. But I'm just starting out with D3, and I can't for the life of me figure out how to chain something together that loops through each object and creates a new row for each, adding to the vertical offset each time.

这适用于直接提供数据的单行,文本标签位于左侧,然后是每个数据点的一系列宽度相等的列。但我刚刚开始使用 D3,我一生都无法弄清楚如何将一些东西链接在一起,循环遍历每个对象并为每个对象创建一个新行,每次都增加垂直偏移。

How can I loop through, creating a for each object in the file, and then creating the text + columns for each row, while preserving the different nested values and array indices?

如何循环遍历,为文件中的每个对象创建一个,然后为每一行创建文本 + 列,同时保留不同的嵌套值和数组索引?

回答by Lars Kotthoff

The key to achieving what you want is to use nested selections. The idea is to pass your whole data object to the first level and create an SVG group for the elements. For each of those elements, the actual visualization is then added in a similar fashion to what you're doing now.

实现您想要的关键是使用嵌套选择。这个想法是将整个数据对象传递到第一级并为元素创建一个 SVG 组。对于这些元素中的每一个,然后以与您现在正在执行的操作类似的方式添加实际的可视化。

Have a look at Mike's tutorial on nested selections. Remember to replace your currently hardcoded data calls with the respective elements, e.g. .data(d.counts)instead of .enter([1, 5, 10, 6]).

看看Mike 的嵌套选择教程。请记住用相应的元素替换您当前的硬编码数据调用,例如.data(d.counts)代替.enter([1, 5, 10, 6]).