Skip to content

Instantly share code, notes, and snippets.

@flunky
Last active March 26, 2017 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flunky/271ae43e1ff832e3617d5c6e4b0afd9e to your computer and use it in GitHub Desktop.
Save flunky/271ae43e1ff832e3617d5c6e4b0afd9e to your computer and use it in GitHub Desktop.
D3 SVG Bar Chart Using Scale
height: 350

This version creates a bar chart that extends across a width x height SVG drawing canvas. It creates d3.scale objects that create a linear mapping from the data values (0 to 42) and indices (0,1,2,3,4,5) to the SVG canvas's vertical (0 to height) and horizontal (0 to width) spans.

See Introducing d3-scale by Mike Bostock for more details on d3.scale and how fundamental the mapping from data coordinates to viewing coordinates is to data visualization.

<!DOCTYPE html>
<script src="//d3js.org/d3.v3.min.js"></script>
<style> .chart rect { fill: steelblue } </style>
<html><body>
<p>Here are the magic numbers from Lost: <span id="data"></span></p>
<svg class="chart"></svg>
<script>
var width = 120;
var height = 300;
var data = [4,8,15,16,23,42];
document.getElementById("data").innerHTML = data;
var x = d3.scale.linear()
.domain([0,6])
.range([0,width]);
var y = d3.scale.linear()
.domain([0,42])
.range([height,0]);
d3.select(".chart")
.attr("width",width)
.attr("height",height)
.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("width",19)
.attr("height",function(d) { return height - y(d); })
.attr("x",function(d,i) { return x(i); })
.attr("y",function(d) { return y(d); });
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment