Skip to content

Instantly share code, notes, and snippets.

@sfrdmn
Created October 17, 2011 16:44
Show Gist options
  • Save sfrdmn/1293048 to your computer and use it in GitHub Desktop.
Save sfrdmn/1293048 to your computer and use it in GitHub Desktop.
DAI 523 - Bar Chart Cont. 10/17
label area
ca 23
ma 456
ne 567
ba 345
ya 34
na 21
// 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;
// this is relavant to my data only.
var xData = "label"
var yData = "area"
/*
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) {
var yMax = d3.max( csv.map( function(d) {
return parseInt( d.area );
}));
var x = d3.scale.ordinal()
.domain(csv.map( function(d) {
return d.label;
}))
.rangeRoundBands([0,w]);
// NOTE: same as rangeBands(), except it removed anti-aliasing between our bars
// try it with rangeBands() and see
var y = d3.scale.linear()
.domain([0,yMax])
.range([0,h-100]);
var barHeight = function(d,i) {
return y(d.area);
}
var xPos = function(d,i) {
return x( d[xData] );
}
var yPos = function(d,i) {
return h - barHeight( d );
}
chart.selectAll("rect.bars").data(csv)
.enter().append("svg:rect")
.attr("class", "bars")
.attr("fill", "coral")
.attr("x", xPos)
.attr("y", yPos)
.attr("width", x.rangeBand() )
.attr("height", barHeight );
// Debugging console log stuff. This is really helpful. We should be using this more.
console.log(
"We want a list of our xaxis labels. We use map for that\n" +
"This is what comes out of that mapping thing: ",
csv.map( function(d) {
return d[xData];
})
);
console.log( "ymax: " + yMax );
console.log( "band width: " + x.rangeBand() );
console.log( "data: ", csv );
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment