访问正确的对象数组列 [英] Accessing the correct array of objects column

查看:80
本文介绍了访问正确的对象数组列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在d3读取TSV文件.然后,我希望将该文件的特定列绘制在一行上.

I am having d3 read a TSV file. Then I want a particular column of that file to be graphed on a line.

我尝试了很多变化,但都带有未定义的错误.

I've tried a lot of variations all with undefined errors.

以下是我要在概念上尝试做的事情:

Below is what I am trying to do in concept:

d3.tsv("file.txt").then( foo => { 

var svg = d3.select("graph").append("svg").attr(etc... )

svg.selectAll(".dot")

    ----->     .data(foo[all indexes]['nameofcolumn'])

            .enter().append("circle") 
            .attr("class", "dot") 
            .attr("cx", function(d, i) { return xScale(i) })
            .attr("cy", function(d) { return yScale(d.y) })
            .attr("r", 5)
            ...etc...

即使我对foo [1] ['columnname']进行硬编码(console.log确认是一个数字),我的图形也无法通过.没有图像,没有错误.

Even if I hardcode foo[1]['columnname'] (which console.log confirms is a number) my graph just falls through. No images, no error.

推荐答案

我认为您对.data()接受的参数感到困惑.您似乎正在从单个数据点将其传递给单个属性.但是,实际上,您应该将整个数据集传递给它.因此,在您的示例中,该名称应为foo:

I think you are getting confused by the argument that .data() takes. You seem to be passing it a single property from a single data point. But, in fact, you should pass it your entire dataset. So in your example, this should just be foo:

// foo: [{ "Date Time": 12:00, T1: 1, T2: 2 }, { "Date Time": 13:00, T1: 3, T2: 3.5 }, ...]

d3.selectAll('.dot')
  .data(foo)
  .enter()
    .append('circle')
    ...

这段代码说:

  1. 选择所有带有 dot 类的元素(尚未创建任何元素,但这很好).
  2. 传入代表我的整个数据集的数组foo.
  3. 如果数据集中尚没有为其创建dom元素的数据点(此刻因为它们是开始,所以现在都将其创建),则添加一个圆.因此,在enter()上,d3将遍历您提供给data()foo数组,并为每个数据点附加一个圆.
  1. select all of the elements with the dot class (there won't have been any created yet, but that's fine).
  2. pass in an array representing my entire dataset, called foo.
  3. if there is any datapoint in the dataset for which there hasn't been a dom element created yet (all of them at the moment because this is the start), then append a circle. So on enter() d3 will loop through the foo array that you provided to data() and append a circle for each data-point.

第二个问题是您似乎错误地设置了cy属性,因为您正在将d.y传递给yScale()函数.相反,您需要从数据中传递正确的属性.

The second issue is that you look to be setting the cy attribute incorrectly, because you are passing in d.y to the yScale() function. Instead you need to pass in the correct property from your data.

因此,在您的示例中,每个数据点都具有T1T2属性.我不确定您要在y轴上代表哪一个,但是可以说它是T1,那么代码应显示为:

So in your example, you have T1 and T2 properties in each of your data-points. I'm not sure which is the one you wish to represent on your y axis, but let say it is T1, then the code should read:

...
.attr('cy', function(d) { return yScale(d.T1); })
...

这篇关于访问正确的对象数组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆