Expert Data Visualization
上QQ阅读APP看书,第一时间看更新

Adding an x-axis with years

The first thing we need to do is add an axis that will show the years. We do this with the addAxis function:

function addAxis(yIncomeScale, yIndexedScale, xScale, xRangeAdjusted) { 
...
var bottomAxis = d3.axisBottom().scale(xScale).ticks(15,"f");
var bottomAxisChart = chart.append("g")
.attr('transform', 'translate( 0 ' + yIndexedScale(100) + ')')
.call(bottomAxis);

bottomAxisChart.selectAll('text')
.attr("transform", "translate(-16 14) rotate(-70)");
...
}

For the center axis, we use the d3.axisBottom function to create an axis based on our xScale. With the ticks function, we specify that we want to have 15 ticks (one for every two years), and we want to format the ticks with a fixed point notation (f).

D3 has an additional module that can be used to format numbers. You can use this library to specify scientific, fixed point, binary, octal, and many other types of notation. Besides notation types, it also contains a large set of other format options to make sure the number output looks exactly as you want. In this book, we'll not pe into the details of the different options. You can look at the excellent D3 API documentation to see what is possible: https://github.com/d3/d3-format#locale_format.

After defining the axis, we add it to a specific group, which we position at the center of the graph by setting the transform property and translating this element using yIndexedScale(100) to position it in the vertical center of the chart. The last thing we do is that we change the position of the text element of the axis so that they are rotated and moved a little bit (translate(-16 14) rotate(-70)). We do this to avoid the labels overlapping with the axis on the right side.

Next, we add the axis on the right side.