Skip to content

Instantly share code, notes, and snippets.

@shawnparrotte
Last active January 30, 2016 21:27
Show Gist options
  • Save shawnparrotte/2e17c4914771f3ea5fe6 to your computer and use it in GitHub Desktop.
Save shawnparrotte/2e17c4914771f3ea5fe6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>GDP Graph</title>
</head>
<body>
<div id="main-graph-container">
</div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
d3.json(url, function(error, rawData){
//*** GRAPH DIMENTIONS ***//
// set the width of the graph to 60% of the window size...
var gWidth = Math.floor( parseInt( $(window).width() ) * .6);
// set the height of the graph to 60% of the graph width...
var gHeight = gWidth * .6;
// set the margins as an object literal...
var margin = { top: 10, right: 10, bottom: 50, left: 50 };
// set the padding for the axes...
var axisPadding = 5;
// set the total height and width of the main svg element...
var tHeight = gHeight + margin.top + margin.bottom;
var tWidth = gWidth + margin.right + margin.left;
//*** DATA CONVERSIONS ***//
// map the dates to an array...
var dates = rawData.data.map( function( d ){ return d[0] });
// map the GPD numbers to an array...
var gdp = rawData.data.map( function( d ){ return d[1] });
// get the max value of gdp...
var maxGDP = d3.max(gdp);
//*** APPEND GRAPH ***//
// append main svg element
var svg = d3.select( "#main-graph-container" )
.append( "svg" )
.attr({ width : tWidth,
height : tHeight
});
// append main graph element
var mainGraph = svg.append( "g" )
.attr({
"transform" : "translate(" + margin.left + "," + margin.top + ")"
});
//*** CREATE SCALES FOR BARS ***//
// ordinal scale for the bar width
var bands = d3.scale.ordinal()
.domain(gdp)
.rangeBands( [0, gWidth], .2);
// linear scale for the bar height
var yScale = d3.scale.linear()
.domain( [0, maxGDP] )
.range( [0, gHeight] );
// function that positions the individual bars to the correct x,y coordinates
function translator(d, i){
console.log(d);
return "translate(" + bands.range()[i] + "," + ( gHeight - yScale(d) ) + ")";
}
//*** MAKE THE BARS ***//
var barGroup = mainGraph.selectAll( "g" )
.data(gdp)
.enter()
.append( "g" )
.attr( "transform", translator );
barGroup.append('rect')
.attr({ fill : "steelblue",
width : bands.rangeBand(),
height : function(d) { return yScale(d); }
});
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment