D3 USA GDP GRAPH

In this example below you will see how to do a D3 USA GDP GRAPH with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by captnstarburst, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright captnstarburst ©
  • HTML
  • CSS
  • JavaScript
    <h1 class="center header top">United States GDP Over the Years</h1>
<h3 class="center header">Data Visualised with ♥ and D3.JS</h3>

<h5 class="description header center"></h5>

<div class="chart"></div>



/*Downloaded from https://www.codeseek.co/captnstarburst/d3-usa-gdp-graph-pVGpmN */
    body{
	background: #4A646C;
}
.top{
	margin-top: 5%;
}
.center{
	display: flex;
	justify-content: center;
}
.header{
	color: white;
	text-shadow: 5px 10px 10px black;
}

.chart{
	width: 1000px; 
	height: 500px;
	margin:0 auto;
	background: white;
	box-shadow: 10px 10px 10px black;
	
}
.bar {
  fill: steelblue;
}

.bar:hover {
  fill: brown;
}

.axis--x path {
  display: none;
}



/*Downloaded from https://www.codeseek.co/captnstarburst/d3-usa-gdp-graph-pVGpmN */
    function makeRequest() {
	httpRequest = new XMLHttpRequest();

	if (!httpRequest) {
		alert("Giving up :( Cannot create an XMLHTTP instance");
		return false;
	}
	httpRequest.onreadystatechange = getContent;
	httpRequest.open(
		"GET",
		"https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"
	);
	httpRequest.send();
}

function getContent() {
	if (httpRequest.readyState === XMLHttpRequest.DONE) {
		if (httpRequest.status === 200) {
			requestReceived(JSON.parse(httpRequest.responseText));
		} else {
			alert("There was a problem with the request.");
		}
	}
}

function requestReceived(data) {
	//  alert(data.data[0][1]);
	
	let formatCurrency = d3.format("$,.2f");
	
	d3
		.select(".description")
		.append("text")
		.text(data.description);

	let totalsArr = [];
	let dateArr = [];

	for (let i = 0; i < data.data.length; i++) {
		totalsArr.push(data.data[i][1]);
		dateArr.push(data.data[i][0]);
	}
	
	let myData = data.data;
	
	let	minDate = new Date(myData[0][0]);
  let	maxDate = new Date(myData[myData.length-1][0]);
	
	

	let margin = {
		top: 30,
		right: 30,
		bottom: 40,
		left: 50
	}
	
	let height = 500 - margin.top - margin.bottom;
	let width = 1000 - margin.left - margin.right ;
	let animateDuration = 500;
	let animateDelay = 10;
	// let barWidth = 3;
	// let barOffset = .5;

	let yScale = d3.scale.linear()
      .range([height, 0])
      .domain([0, d3.max(myData, function(d) {
        return d[1];
      })]);
			
		// d3.scale
		// .linear()
		// .domain([0, d3.max(totalsArr)])
		// .range([0, height]);

	let xScale = 
			d3.scale
		.ordinal()
		.domain(d3.range(0, myData.length))
		.rangeBands([0, width]);
	// 		d3.time.scale()
	// .ordinal()
	// .domain([minDate, maxDate])
	// .rangeBands([0, width]);

	
	// d3.scale
	// 	.ordinal()
	// 	.domain(d3.range(0, totalsArr.length))
	// 	.rangeBands([0, width]);

	let colors = d3.scale
		.linear()
		.domain([0, totalsArr.length])
		.range(["#647489", "#FF7A00"]);

	let tooltip = d3
		.select("body")
		.append("div")
		.style("position", "absolute")
		.style("background", "#f4f4f4")
		.style("padding", "15px")
		.style("border", "1px solid #333")
		.style("border-radius", "5px")
		.style("opacity", "0");

	let myChart = d3
		.select(".chart")
		.append("svg")
		.attr("width", width + margin.right + margin.left)
		.attr("height", height + margin.bottom + margin.top)
		.append('g')
		.attr('transform', 'translate('+margin.left+','+ margin.top +')')
		.style("background", "#f4f4f4")
		.selectAll("rect")
		.data(myData)  
		.enter()
		.append("rect")
		.style("fill", function(d, i) {
			return colors(i);
		})
		.attr("width", xScale.rangeBand())
		.attr("height", 0)
		.attr("x", function(d, i) {
			console.log(d[0]);
			return xScale(d[0]);
			
		})
		.attr("y", height)
		.on("mouseover", function(d) {
			tooltip.transition().style("opacity", 1);
			tooltip
				.html("$"+d[0] + "0 Billion ")
				.style("left", d3.event.pageX + "px")
				.style("top", d3.event.pageY + "px");
			d3.select(this).style("opacity", 0.5);
		})
		.on("mouseout", function(d) {
			tooltip.transition().style("opacity", 0);
			d3.select(this).style("opacity", 1);
		});

	myChart
		.transition()
		.attr("height", function(d) {
			
			return yScale(d[1]);
		
		})
		.attr("y", function(d) {
			return height - yScale(d[1]);
		})
		.duration(animateDuration)
		.delay(function(d,i){		
			return i * animateDelay
		})
		.ease('elastic');

	let vScale = d3.scale
		.linear()
		.domain([0, d3.max(totalsArr)])
		.range([height, 0]);

	let hScale = d3.scale
		.ordinal()
		.domain(d3.range(0, dateArr.length))
		.rangeBands([0, width]);	
	
	let vAxis = d3.svg.axis()
		.scale(vScale)
		.orient('left')
		.ticks(10, " ")
		.tickPadding(5);
	
	let vGuide = d3.select('svg')
		.append('g')
			vAxis(vGuide)
			vGuide.attr('transform', 'translate('+ margin.left +','+ margin.top + ')')
			vGuide.selectAll('path')
				.style('fill', 'none')
				.style('stroke', '#000')
			vGuide.selectAll('line')
				.style('stroke', '#000');
	
	let hAxis = d3.svg.axis()
		.scale(hScale)
		.orient('bottom')
		.ticks(d3.time.years, 10);
	
	let hGuide = d3.select('svg')
		.append('g')
			hAxis(hGuide)
			hGuide.attr('transform', 'translate('+margin.left+','+ (height + margin.top)+')')
			hGuide.selectAll('path')
				.style('fill', 'none')
				.style('stroke', '#000')
			hGuide.selectAll('line')
				.style('stroke', '#000')	

}

makeRequest();


Comments