Preparing the SVG structure for the chart and the axis

As we are not creating a complex visualization with lots of functionality (yet), the preparation is relatively simple. However, it is still considered a good practice to separate one-off code executions from the remaining functions, or at least  have a section within your code that covers that aspect in a segregated way.

In the case of the Mastering QS bar chart, the preparation will revolve around appending an SVG element to the extension div. This is achieved using the d3 function, as follows:

//MasteringQSBarChart.js - scope.prep() (snippet)
scope.svg = d3.select($element.children()[0])
.append('svg')

scope.svg.append('g')
.attr('class', 'canvas')

scope.svg.append('g')
.attr('class', 'x-axis')

scope.svg.append('g')
.attr('class', 'y-axis')

With the SVG, we also added three g elements, which allow relevant elements to be grouped in the latter part of the code. This provides a better overview but also the ability to control some fixed styling via the classes.

This will create the following HTML structure:

Furthermore, we will also include the axis definitions into the preparation section to declare that our x-axis will be ordinal (categories) and our y-axis linear. These are created using the d3.svg.axis() function, as follows:

//MasteringQSBarChart.js - scope.prep() (snippet)
scope.x = d3.scale.ordinal()
scope.y = d3.scale.linear().nice();
scope.xAxis = d3.svg.axis()
scope.yAxis = d3.svg.axis();

Once the preparation is complete, we call the initialization function:

//MasteringQSBarChart.js - scope.prep() (snippet)
scope.init(scope.element, scope.layout)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.183.153