4.7 KiB
4.7 KiB
id | title | required | challengeType | videoUrl | localeTitle | |||
---|---|---|---|---|---|---|---|---|
587d7fad367417b2b2512bdf | Add Axes to a Visualization |
|
6 | 将轴添加到可视化 |
Description
axisLeft()
和axisBottom()
分别渲染y轴和x轴。 (轴是轴的复数形式)。以下是在先前的挑战中基于xScale
创建x轴的示例: const xAxis = d3.axisBottom(xScale);
下一步是在SVG画布上渲染轴。为此,您可以使用常规SVG组件g
元素。 g
代表组。与rect
, circle
和text
,轴在渲染时只是一条直线。因为它是一个简单的形状,使用g
作品。最后一步是应用transform
属性将轴定位在SVG画布上的正确位置。否则,该线将沿着SVG画布的边框渲染,并且不可见。 SVG支持不同类型的transforms
,但定位轴需要translate
。当它应用于g
元素时,它会按给定的数量上下移动整个组。这是一个例子: const xAxis = d3.axisBottom(xScale);上面的代码将x轴放在SVG画布的底部。然后它作为参数传递给
svg.append( “G”)
.attr(“transform”,“translate(0,”+(h - padding)+“)”)
.CALL(x-轴);
call()
方法。除了translate
参数的形式为(x,0)之外,y轴的工作方式是相同的。因为translate
是上面attr()
方法中的字符串,所以可以使用连接来包含其参数的变量值。 Instructions
axisLeft()
方法在名为yAxis
的变量中创建y轴。然后使用g
元素渲染轴。确保使用transform
属性将轴转换为右边的填充单元数量,然后降低0个单位。记得call()
轴。 Tests
tests:
- text: 您的代码应使用<code>axisLeft()</code>方法, <code>yScale</code>作为参数传递。
testString: 'assert(code.match(/\.axisLeft\(yScale\)/g), "Your code should use the <code>axisLeft()</code> method with <code>yScale</code> passed as the argument.");'
- text: 'y轴<code>g</code>元素应具有<code>transform</code>属性以将轴平移(60,0)。'
testString: 'assert($("g").eq(1).attr("transform").match(/translate\(60\s*?,\s*?0\)/g), "The y-axis <code>g</code> element should have a <code>transform</code> attribute to translate the axis by (60, 0).");'
- text: 您的代码应该调用<code>yAxis</code> 。
testString: 'assert(code.match(/\.call\(yAxis\)/g), "Your code should call the <code>yAxis</code>.");'
Challenge Seed
<body>
<script>
const dataset = [
[ 34, 78 ],
[ 109, 280 ],
[ 310, 120 ],
[ 79, 411 ],
[ 420, 220 ],
[ 233, 145 ],
[ 333, 96 ],
[ 222, 333 ],
[ 78, 320 ],
[ 21, 123 ]
];
const w = 500;
const h = 500;
const padding = 60;
const xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding]);
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", (d) => xScale(d[0]))
.attr("cy",(d) => yScale(d[1]))
.attr("r", (d) => 5);
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text((d) => (d[0] + "," + d[1]))
.attr("x", (d) => xScale(d[0] + 10))
.attr("y", (d) => yScale(d[1]))
const xAxis = d3.axisBottom(xScale);
// Add your code below this line
const yAxis = undefined;
// Add your code above this line
svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
// Add your code below this line
// Add your code above this line
</script>
</body>
Solution
// solution required