Created
February 16, 2012 05:51
-
-
Save ashleybot/1842440 to your computer and use it in GitHub Desktop.
D3.js Basic Vertical Bar Chart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// simple array | |
var data = [8, 12, 15, 30, 43]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// variables for chart width and height | |
var w = 20, | |
h = 50; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chart = d3.select(".charts").append("svg") | |
.attr("class", "chart") | |
.attr("width", w * data.length) | |
.attr("height", h); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x = d3.scale.linear() | |
.domain([0, 1]) | |
.range([0, w]); | |
var y = d3.scale.linear() | |
.domain([0, 50]) | |
.rangeRound([0, h]); //rangeRound is used for antialiasing |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// x and y are the lower-left position of the bar | |
// width is the width of the bar | |
// height is the height of the bar | |
// for crisp edges use -.5 (antialiasing) | |
chart.selectAll("rect") | |
.data(data) | |
.enter().append("rect") | |
.attr("x", function(d, i) { return x(i) - .5; }) | |
.attr("y", function(d) { return h - y(d) - .5; }) | |
.attr("width", w) | |
.attr("height", function(d) { return y(d); } ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// horizontal line for the x-axis | |
chart.append("line") | |
.attr("x1", 0) | |
.attr("x2", w * data.length) | |
.attr("y1", h - .5) | |
.attr("y2", h - .5) | |
.style("stroke", "#000"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment