Coding Visualization Tutorial 2: Functions

written

Function is a block of code to perform a particular task. You can use function to reduce repetitive code and improve readability. Function can be a separate object or part of another object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// general syntax
function name(variables) {
  // execute task
}

// for example, multiple two numbers
function multiply(n1, n2) {
  return n1 * n2;
}

// this call return 12 and assign to n
var n = multiply(3, 4);

// This function selects div tag with id="canvas-svg"
var canvas_svg = d3.select("#canvas-svg");

// Append svg element to canvas_svg div
var svg = canvas_svg.append("svg");

You can call functions in a chain. It’s commonly used in D3 code.

1
2
3
4
// This statement calls select and append on select result
// It's equivalent to two statements above.
var svg = d3.select("#canvas-svg")
            .append("svg");

Even more chaining:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var svg = d3.select("#canvas-svg")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Above code do the following:

// Append svg element to #canvas-svg div, this statement returns svg element
d3.select("#canvas-svg").append("svg");

// Set width and height of svg element
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)

// Append g element to svg element
  .append("g")

// Set transform attribute of above g element
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

After that, you’ll get canvas-svg div like below:

1
2
3
4
5
6
7
<div id="canvas-svg">
  <svg width="800" height="450">
    <g transform="translate(50,20)">
      <!-- visualization elements -->
    </g>
  </svg>
</div>

See example document here:

https://vida.io/documents/9Pst6wmB83BgRZXgx

See tutorial video here:


Comments