官术网_书友最值得收藏!

Adding the y-axis with the index values and the horizontal marker lines

We've seen how we've already the x-axis and one of the y-axes. The final axis is the one showing the index values:

function addAxis(yIncomeScale, yIndexedScale, xScale, xRangeAdjusted) { 
...
var steps = d3.range(100-xRangeAdjusted, 100+xRangeAdjusted + 1, 2);
var leftAxis = d3.axisLeft().scale(yIndexedScale).tickValues(steps);
var leftAxisSVG = chart.append("g")
.attr('transform', 'translate( 0 ' + yIndexedScale(100 + xRangeAdjusted) + ')')
.call(leftAxis);

leftAxisSVG.selectAll('text')
.text(function(d) {
return d === 100 ? "no change" : d3.format("+")(d - 100);
})
.attr("stroke", "#aaa")
.attr("dy", "-0.5em")
.attr("dx", "1em")
.style("font-weight", "100")
.attr("text-anchor", "start");

leftAxisSVG.selectAll('.domain').remove();
leftAxisSVG.selectAll('.tick line')
.attr("x1", width)
.attr("stroke", "#ddd")
.attr("opacity", "0.6");
...
}

The first thing we do here is define the number of ticks we want to show. We use the d3.range function for this, which returns an array from 100-xRangeAdjusted (90) to 100+xRangeAdjusted+1 (111), with a gap of two. So, in this case we get back an array with values: 90, 92, 94 ... 108, 110. We use these values as parameters of the tickValues function when we create the axis. This means we get steps.length ticks, where each tick has its data set to the corresponding value from the steps array. Next, we append the axis to the chart and position it correctly. However, we're not done yet. We next select all the text elements of this axis, and change the text using d3.format. Negative values will have a - prepended, and positive ones a +. If the value is 100, we set the tick text to no change. At the same time, we also set some text styles to property format the text (note that we've also could have done this directly through CSS). The final step we take here is adding the horizontal marker lines. For this, we first remove the vertical axis (which can be found by selecting the domain class), and after that we change the width, stroke, and opacity of the ticks to transform them to the horizontal marker lines.

At this point, the complete chart is drawn, and by using the axis we can understand what this chart represents:

In the last section, we're going to add some interactivity to this chart.

主站蜘蛛池模板: 黄平县| 保康县| 新营市| 东丰县| 肥东县| 大足县| 广元市| 鄄城县| 襄垣县| 丰原市| 香港 | 巩留县| 新干县| 桦川县| 营口市| 石景山区| 东丰县| 麟游县| 唐河县| 龙江县| 黄梅县| 宜州市| 凤城市| 丽水市| 广汉市| 亚东县| 九台市| 舒城县| 胶南市| 昌乐县| 化州市| 滕州市| 灌南县| 东乌珠穆沁旗| 济阳县| 西林县| 韶关市| 定结县| 乐安县| 淅川县| 蒙阴县|