Skip to content

Instantly share code, notes, and snippets.

@danasilver
Last active August 29, 2015 14:05
Show Gist options
  • Save danasilver/0ae7fa639d7bfbffa146 to your computer and use it in GitHub Desktop.
Save danasilver/0ae7fa639d7bfbffa146 to your computer and use it in GitHub Desktop.
Bar chart with linear x scale
hours votes
0 3
1 5
2 3
3 7
4 1
5 5
6 0
7 6
8 4
9 2
10 1
11 8
12 2
<!doctype html>
<meta charset="utf-8">
<style>
rect {
fill: steelblue;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear();
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").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 + ")");
d3.csv("data.csv", type, function (error, data) {
x
.domain(d3.extent(data, function (d) { return d.hours; }))
.range([width / data.length / 2, width - width / data.length / 2])
y
.domain([0, d3.max(data, function (d) { return d.votes; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function (d) { return (x(d.hours) - width / data.length / 2) + 1; })
.attr("width", (width / data.length) - 1)
.attr("y", function (d) { return y(d.votes); })
.attr("height", function (d) { return height - y(d.votes); });
});
function type (d) {
d.hours = +d.hours;
d.votes = +d.votes;
return d;
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment