SVG D3.js bar chart

This has been driving me up the wall. I haven’t felt so stupid in a long time. Anyway, since I managed it finally, here is some code:

<script type="text/javascript" src="d3/d3.v3.min.js"></script>

<style type="text/css">
.axis text {
font: 10px sans-serif;

.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
<div id="chart"></div>

<script type="text/javascript">
var margin = {top: 10, right: 10, bottom: 30, left: 50},
width = 500 - margin.left - margin.right,
height = 300 - - margin.bottom;

var x = d3.scale.linear()
.domain([0, 20])
.range([0, width]);

var y = d3.scale.linear()

var xAxis = d3.svg.axis()

var yAxis = d3.svg.axis()

var svg ="#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + + ")");

.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")

.attr("class", "y axis")

var data = [[1,100],[6,20],[20, 50]];

var bars = svg.selectAll("rect")
.attr("x", function(d) {return x(d[0]) - 5;})
.attr("y", function(d) {return y(d[1]);})
.attr("height", function(d) {return height - y(d[1]);})



and the output:


Adapted from this example on jsfiddle. Another good source of information is Scott Murray’s d3.js tutorials particularly scales and axes.

1 thought on “SVG D3.js bar chart

  1. clockwerx

    Ah, d3 nearly made my head explode until I realized what it wanted.

    I still think it makes no sense half of the time, just to be difficult

Comments are closed.