简体   繁体   English

无法通过数组在d3中创建条形图

[英]Trouble creating a bar chart in d3 from an array

I have a json file that I loop through for specific key/value pairs. 我有一个json文件,可以循环查看特定的键/值对。 The output is pushed to an array of the form: 输出被推送到以下形式的数组:

var output = ["key1", "value1", "key2", "value2", ... "key(n)", "value(n)"]

What I'd like to do is generate a column chart in d3.js where the key corresponds to the bar label, and the heigh corresponds to the value. 我想做的是在d3.js中生成一个柱形图,其中键对应于条形标签,而高度对应于值。

I'm struggling with this seemingly simple task. 我正在努力完成这项看似简单的任务。 Any advice would be appreciated. 任何意见,将不胜感激。

Thanks in advance. 提前致谢。

Might be easier to structure the output array as follows: 可能更容易构造输出数组,如下所示:

var output = [{"key": "key1", "value": "value1"}, {"key": "key2", "value": "value2"}, ...]

Then, in the d3 code, you can create data using this this array, and simply return the appropriate information depending on whether you need to determine the bar label or its height. 然后,在d3代码中,您可以使用此数组创建数据,并根据需要确定条形标签或其高度来简单地返回适当的信息。 Does that make sense? 那有意义吗?

When writing the bar labels, for instance, it would look something like this: 例如,在编写条形标签时,它将看起来像这样:

var labels = d3.selectAll("labels")
    .data(output)
    .enter()
    .append("g")
    .text( function(d,i) {
        return d.key;
    })

Without knowing exactly what the json file looks like, I can't tell you how to construct the output array in this form, but given that you have an array that looks like 不知道确切的json文件是什么样子,我无法告诉您如何以这种形式构造输出数组,但是鉴于您有一个看起来像这样的数组

var original_output = ["key1", "value1", "key2", "value2", ... "key(n)", "value(n)"]

you could construct the new output array like this: 您可以像这样构造新的输出数组:

var new_output = [];
for (var i = 0; i < original_output.length; i=i+2) {
    new_output.push({"key": original_output[i], "value": original_output[i + 1]})
}

This solution assumes that the key and value for each pair are right by each other and in the right order. 该解决方案假定每对键和值彼此正确且顺序正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM