---
id: 587d7fa9367417b2b2512bce
title: Dynamically Set the Coordinates for Each Bar
required:
- src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
videoUrl: ''
localeTitle: 动态设置每个条形的坐标
---
## Description
最后一个挑战是为dataset
每个点创建一个矩形并将其附加到svg
元素以表示一个条形。不幸的是,它们都堆叠在一起。矩形的放置由x
和y
属性处理。他们告诉D3从哪里开始在svg
区域中绘制形状。最后一个挑战将它们设置为0,因此每个栏都放在左上角。对于条形图,所有条形应位于相同的垂直水平,这意味着所有条形的y
值保持不变(为0)。但是,在添加新柱时, x
值需要更改。请记住,较大的x
值会将项目推向更远的位置。当您浏览dataset
的数组元素时,x值应该会增加。 D3中的attr()
方法接受回调函数来动态设置该属性。回调函数有两个参数,一个用于数据点本身(通常为d
),另一个用于数组中数据点的索引。索引的第二个参数是可选的。这是格式: selection.attr(“property”,(d,i)=> {
/ *
* d是数据点值
* i是数组中数据点的索引
* /
})
重要的是要注意,您不需要编写for
循环或使用forEach()
来迭代数据集中的项。回想一下, data()
方法解析数据集,并且data()
之后链接的任何方法对数据集中的每个项目运行一次。
## Instructions
更改x
属性回调函数,使其返回索引时间30. 注意
每个条的宽度为25,因此将每个x
值增加30会在条之间增加一些空间。任何大于25的值都可以在此示例中使用。
## Tests
```yml
tests:
- text: 第一个rect
的x
值应为0。
testString: 'assert($("rect").eq(0).attr("x") == "0", "The first rect
should have an x
value of 0.");'
- text: 第二个rect
的x
值应为30。
testString: 'assert($("rect").eq(1).attr("x") == "30", "The second rect
should have an x
value of 30.");'
- text: 第三个rect
的x
值应为60。
testString: 'assert($("rect").eq(2).attr("x") == "60", "The third rect
should have an x
value of 60.");'
- text: 第四个rect
的x
值应为90。
testString: 'assert($("rect").eq(3).attr("x") == "90", "The fourth rect
should have an x
value of 90.");'
- text: 第五个rect
的x
值应为120。
testString: 'assert($("rect").eq(4).attr("x") == "120", "The fifth rect
should have an x
value of 120.");'
- text: 第六个rect
的x
值应为150。
testString: 'assert($("rect").eq(5).attr("x") == "150", "The sixth rect
should have an x
value of 150.");'
- text: 第七个rect
的x
值应为180。
testString: 'assert($("rect").eq(6).attr("x") == "180", "The seventh rect
should have an x
value of 180.");'
- text: 第八个rect
的x
值应为210。
testString: 'assert($("rect").eq(7).attr("x") == "210", "The eighth rect
should have an x
value of 210.");'
- text: 第九个rect
的x
值应为240。
testString: 'assert($("rect").eq(8).attr("x") == "240", "The ninth rect
should have an x
value of 240.");'
```
## Challenge Seed
## Solution
```js
// solution required
```