- Expert Data Visualization
- Jos Dirksen
- 360字
- 2021-07-09 18:22:48
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.
- 計算機圖形學編程(使用OpenGL和C++)(第2版)
- C# Programming Cookbook
- 基于Java技術的Web應用開發
- PyTorch Artificial Intelligence Fundamentals
- 青少年信息學競賽
- 利用Python進行數據分析
- RESTful Java Web Services(Second Edition)
- Instant PHP Web Scraping
- Photoshop CC移動UI設計案例教程(全彩慕課版·第2版)
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛上編程(全彩)
- SQL Server 2008實用教程(第3版)
- 前端架構設計
- React and React Native
- VC++ 2008專題應用程序開發實例精講
- Unity與C++網絡游戲開發實戰:基于VR、AI與分布式架構