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

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.

主站蜘蛛池模板: 海原县| 永善县| 阜平县| 文昌市| 高淳县| 鄂尔多斯市| 繁峙县| 涪陵区| 新河县| 贞丰县| 康定县| 鸡泽县| 合肥市| 永吉县| 三都| 东港市| 南昌县| 临颍县| 株洲市| 汝州市| 桑日县| 黄龙县| 丰顺县| 上蔡县| 陵川县| 霍城县| 富顺县| 齐河县| 德昌县| 沙河市| 万山特区| 盐津县| 达州市| 揭东县| 库尔勒市| 昭通市| 葵青区| 崇信县| 太白县| 兴隆县| 海淀区|