Initializing the SVG chart

This part covers all the calculations around the settings and sizing of the visualization chart. This is where you can read your settings from the property panel.

In this particular example, in the initialization part, we will conduct three exercises:

  • Setting the width and height of the SVG$element.width() and $element.height() provide the dynamic width and height of the extension. To ensure the axis and other elements of the visualization have enough space on the canvas, we apply a margin and recalculate the width and height, less the margin, for visualization purposes:
//MasteringQSBarChart.js - scope.init() (snippet)
scope.margin = {top: 30, right: 30, bottom: 30, left: 50}
scpe.width = $element.width() - scope.margin.right - scope.margin.left
scope.height = $element.height() - scope.margin.top - scope.margin.bottom
  • (Re)positioning the canvas, and the x-axis and y-axis elements, based on the SVG's height and width: The canvas and the axis are positioned relative to the parent SVG, based on the defined margins:
//MasteringQSBarChart.js - scope.init() (snippet)
scope.svg.select('.canvas')
.attr('transform', 'translate('+scope.margin.left+',5)')

scope.svg.selectAll('.x-axis')
.attr('transform', 'translate('+scope.margin.left+','+parseInt(scope.height+5)+')')

scope.svg.selectAll('.y-axis')
.attr('transform', 'translate('+scope.margin.left+',5)')

It's worth mentioning we are deliberately moving all elements vertically by 5 px to ensure the y-axis tick values don't get cut off at the top.

  • Defining the x-axis and y-axis range: An axis within d3 has two essential interval properties. One is the real range on the SVG canvas, set in pixels. The other one is the domain, which represents the min and max value of how the underlying data should be positioned within the range.

If, for example, the range is [0, 100px], and the domain [50,100], a data value of 50 will be positioned at the very bottom of the y-axis, and 75 will be placed in the middle of it. If a range does not make sense to be defined owing to an ordinal axis, you can use rangeRoundBands, which evenly spaces out the domain values:

//MasteringQSBarChart.js - scope.init() (snippet)
scope.y.range([scope.height, 0]);
scope.x.rangeRoundBands([0, scope.width], 0.1);

Furthermore, here is an excellent opportunity to define any other settings or properties that will be used when visualizing the data, for example, the bar color. Once the initialization is complete, the rendering function of the chart is ready to be called:

//MasteringQSBarChart.js - scope.init() (snippet)
scope.bar_color = layout.barColor.color;
..................Content has been hidden....................

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