Database Reference
In-Depth Information
Listing 7.4 D3.js: Drawing the blue square programmatically
<html>
<head>
<!-- Include a recent version of the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
// Create a new SVG object, and append it
// to the <body> element of the page.
var svgObject = d3.select("body")
.append("svg");
// Now, add some size, color, and position information
// to the SVG object we've created. In this example,
// we will create a blue square with a black border,
// just like the one in the pure SVG example.
var blueSquare = svgObject.append("rect")
.attr("x", 57)
.attr("y", 195)
.attr("width", 100)
.attr("height", 100)
.attr("fill", "#0000ff")
.attr("stroke","#000000")
.attr("stroke-width","1px");
</script>
svg</body>
</html>
In Listing 7.4, the code for creating a blue square seems to be a bit more complex
than the simple, raw XML we used in the SVG example in Listing 7.3. However, cre-
ating shapes is not the real point of D3.js; we want to take the next step and manipu-
late shapes into patterns for the visualization of data.
Building on what we learned in the previous example, we will now create a simple
bar chart using D3.js that displays the relative ages of all United States presidents at the
time of inauguration. This example, although very simple, illustrates some of the use-
ful features that make D3.js so powerful. Listing 7.5 presents the code.
We start by defining our sample dataset using a simple JavaScript array called
usaPresidentAges . We will also create an svgObject for our base graphic as we
did in the blue-square example. The d3.scale.linear function helps us define a
dynamic range for the width of our chart.
One of the great features of D3.js is the ability to iterate over values in a
dataset and apply a function to assign values to parts of the visualization. The
. data(usaPresidentAges) method iterates through each of the values in our
 
 
Search WWH ::




Custom Search