Skip to content

Instantly share code, notes, and snippets.

@emeeks
Last active March 18, 2016 15:14
Ch. 2, Fig. 15 - D3.js in action

This is the code for Chapter 2, Figure 15 from D3.js in Action that creates rectangles with height based on the data bound to the selection. The rectangles are positioned along the X axis based on the array position of the datapoint that each retangle represents and each rectangle is offset based on its height so as to be drawn as a typical bar chart. This offsetting is necessary with SVG rectangles because they are drawn down from their XY position.

<html>
<head>
<title>D3 in Action Chapter 2 - Example 5</title>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<style>
svg {
height: 500px;
width: 500px;
border: 1px solid gray;
}
</style>
<body>
<div>
<svg>
</svg>
</div>
</body>
<footer>
<script>
d3.select("svg")
.selectAll("rect")
.data([15, 50, 22, 8, 100, 10])
.enter()
.append("rect")
.attr("width", 10)
.attr("height", function(d) {return d})
.style("fill", "blue")
.style("stroke", "red")
.style("stroke-width", "1px")
.style("opacity", .25)
.attr("x", function(d,i) {return i * 10})
.attr("y", function(d) {return 100 - d})
</script>
</footer>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment