Skip to content

Instantly share code, notes, and snippets.

@sampathweb
Last active May 12, 2016 21:59
Show Gist options
  • Save sampathweb/49c42630e4ce65941bf5c6191cdb7afe to your computer and use it in GitHub Desktop.
Save sampathweb/49c42630e4ce65941bf5c6191cdb7afe to your computer and use it in GitHub Desktop.
Basic Bar Chart
license: mit

Basic Bar Chart

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Basic Bar Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style type="text/css">
/* CSS style rules will go here */
.axis line,
.axis path {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font: 12px sans-serif;
}
rect.bar {
fill: steelblue;
}
text.bar {
font: 12px sans-serif;
}
svg {
background-color: #eee;
}
</style>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">
// D3 code will go here
//Array of dummy data values (simple!)
var dataset = [ 5, 10, 12, 17, 23, 25, 21, 16, 11, 14, 22, 18, 9, 3 ];
var margin = {top: 20, right: 20, bottom: 50, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#viz")
.append("svg")
.attr({
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom
})
.append("g")
.attr("transform", "translate(" + [margin.left, margin.top] + ")");
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1);
var yScale = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
xScale.domain(d3.range(dataset.length));
yScale.domain([0, d3.max(dataset)]);
// Build the viz
var rects = svg.selectAll("rect.bar")
.data(dataset);
rects.enter()
.append("rect")
.classed("bar", true)
.attr({
x: function(d, i) { return xScale(i); },
y: function(d) { return yScale(d); },
height: function(d) { return height - yScale(d); },
width: xScale.rangeBand()
});
svg.selectAll("text.bar")
.data(dataset)
.enter()
.append("text")
.classed("bar", true)
.attr({
x: function(d, i) { return xScale(i) + xScale.rangeBand()/3;},
y: function(d) { return yScale(d) - 2; }
})
.text(function(d) { return d; });
svg.append("g")
.classed("x axis", true)
.attr("transform", "translate(" + [0, height] + ")")
.call(xAxis);
svg.append("g")
.classed("y axis", true)
.call(yAxis);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment