Skip to content

Instantly share code, notes, and snippets.

@efekarakus
Last active October 15, 2015 04:23
Show Gist options
  • Save efekarakus/35d4cd9c6952666c37e6 to your computer and use it in GitHub Desktop.
Save efekarakus/35d4cd9c6952666c37e6 to your computer and use it in GitHub Desktop.
Simple Bar Chart
var bar = function() {
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 500,
height = 200;
function chart(selection) {
selection.each(function(data) {
var svg = d3.select(this).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
var barWidth = width / data.length;
var y = d3.scale.linear()
.domain([0, d3.max(data)])
.range([height, 0]);
var bars = svg.selectAll(".bar")
.data(data).enter()
.append("g")
.attr("class", "bar");
bars.append("rect")
.attr("x", function(d, i) { return i*barWidth; })
.attr("y", function(d, i) { return y(d); })
.attr("width", barWidth)
.attr("height", function(d, i) { return height - y(d); });
});
}
chart.margin = function(_) {
if (!arguments.length) return undefined;
margin = _;
return chart;
}
chart.width = function(_) {
if (!arguments.length) return undefined;
width = _;
return chart;
}
chart.height = function(_) {
if (!arguments.length) return undefined;
height = _;
return chart;
}
return chart;
}
<html>
<head>
<meta charset="utf-8">
<title>Simple Bar Chart</title>
<style>
g.bar {
stroke: #000;
stroke-width: 1;
fill: #00FF96;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="./bar.js" charset="utf-8"></script>
<script>
var data = [50, 10, 20, 30, 40, 50, 40, 30, 20, 15];
var chart = bar()
.width(700)
.height(50)
.margin({top: 10, left: 5, right: 5, bottom: 10});
d3.select("body")
.datum(data)
.call(chart);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment