Skip to content

Instantly share code, notes, and snippets.

@flunky
Last active March 26, 2017 04:37
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/94badfbd557998a17c87327eaebad2a3 to your computer and use it in GitHub Desktop.
Save flunky/94badfbd557998a17c87327eaebad2a3 to your computer and use it in GitHub Desktop.
D3 SVG Bar Chart With Axes
height: 450

Here we add x and y axes using the d3.svg.axis objects. We labelled both xAxis and yAxis as class axis so the CSS code above can specify that the axis geometry is not filled. We have also changed the x scale to ordinal.

We have also used SVG grouping nodes. Here's an example of how they work:

<svg>
    <g transform="translate(10,20)">
        <rect x="30" y="40"></rect>
    </g>
</svg>

These grouping nodes can transform the SVG geometry inside of them. So the rectangle above would actually be positioned at x=40, y=60.

<!DOCTYPE html>
<script src="//d3js.org/d3.v3.min.js"></script>
<style>
.chart rect { fill: steelblue }
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
</style>
<html><body>
<p>Here are the magic numbers from Lost: <span id="data"></span></p>
<svg class="chart"></svg>
<script>
var margin = 30;
var width = 120;
var height = 300;
var data = [4,8,15,16,23,42];
document.getElementById("data").innerHTML = data;
var x = d3.scale.ordinal()
.domain([0,1,2,3,4,5])
.rangeBands([0,width]);
var y = d3.scale.linear()
.domain([0,42])
.range([height,0]);
var chart = d3.select(".chart");
chart.attr("width",width + 2*margin)
.attr("height",height + 2*margin)
.append("g")
.attr("transform","translate(" + margin + "," + margin + ")")
.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); });
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(1);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
chart.append("g")
.attr("transform", "translate(" + margin + "," + (height+margin) + ")")
.attr("class","axis")
.call(xAxis);
chart.append("g")
.attr("transform", "translate(" + margin + "," + margin + ")")
.attr("class","axis")
.call(yAxis);
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment