Created
October 12, 2011 20:33
-
-
Save sfrdmn/1282451 to your computer and use it in GitHub Desktop.
DAI 523 - Bar Chart 10/12
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
// If you rename your script, don't forget to change the <script> tag in the HTML file!!! | |
var w = 800; // width | |
var h = 600; // height | |
var marginT = 20; | |
var marginL = 20; | |
/* | |
First append SVG to the body | |
*/ | |
d3.select("body").append("svg:svg") | |
.attr("width", w+marginL) | |
.attr("height", h+marginT); | |
/* | |
Select the svg, append a group, name the group, and apply margin if you want one | |
(save the selection) | |
*/ | |
var chart = d3.select("svg").append("svg:g") | |
.attr("class", "chart") | |
.attr("transform", "translate(" + marginL + "," + marginT + ")" ); | |
chart.append("svg:rect") | |
.attr("width", w ) | |
.attr("height", h ) | |
.attr("fill", "lavender" ); | |
/* | |
Load your data. All code which needs access to the data will go in the curly brackets. | |
Make sure 'data/your_data.csv' matches the name and location of your data file. | |
If your data is JSON formatted, simply use 'd3.json' insead of 'd3.csv' | |
*/ | |
var stuff; | |
d3.csv( "data/data.csv", function(csv) { | |
console.log( csv ); | |
stuff = csv; | |
var yMax = d3.max( csv.map( function(d) { | |
console.log( parseInt(d.area) ); | |
return parseInt( d.area ); | |
})); | |
console.log( "ymax: " + yMax ); | |
var x = d3.scale.ordinal() | |
.domain([0,1,2,3,4,5]) | |
.rangeBands([0,w]); | |
//console.log( "csv label " + d3.values(csv) ); | |
console.log( "x function: " + x(csv[0].label) ); | |
console.log( "band width: " + x.rangeBand() ); | |
console.log( "data: " + csv ); | |
var y = d3.scale.linear() | |
.domain([0,yMax]) | |
.range([0,h-100]); | |
console.log( "function output: " + y(200) ); | |
var barHeight = function(d,i) { | |
return y(d.area); | |
} | |
var xPos = function(d,i) { | |
return i*x.rangeBand(); | |
} | |
var yPos = function(d,i) { | |
return h - barHeight( d.area ); | |
} | |
chart.selectAll("rect.bars").data(csv) | |
.enter().append("svg:rect") | |
.attr("class", "bars") | |
.attr("fill", "lemonchiffon") | |
.attr("x", xPos ) | |
.attr("y", 0 ) | |
.attr("width", x.rangeBand() ) | |
.attr("height", barHeight ); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment