Built with blockbuilder.org
Created
March 31, 2018 10:53
-
-
Save yanhann10/3a8e0195999b78ff7c8e7dd5241309c0 to your computer and use it in GitHub Desktop.
area 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
license: mit |
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
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
.area { | |
fill: teal; | |
stroke: none; | |
} | |
} | |
</style> | |
</head> | |
<body> | |
<script> | |
url="https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"; | |
//chart margins and range of w and hs of the levels inside chart | |
var margin = {top: 20, right: 20, bottom: 70, left: 40}, | |
w = 800 - margin.left - margin.right, | |
h = 500 - margin.top - margin.bottom; | |
var parseDate = d3.timeParse("%Y-%m-%d"); | |
var svg = d3 | |
.select("body") | |
.append("svg") | |
.attr("w", w + margin.left + margin.right) | |
.attr("h", h + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", | |
"translate(" + margin.left + "," + margin.top + ")"); | |
d3.json(url, function(data) { | |
resultData = data.data; | |
resultData.forEach(function(d){ | |
d[0] = (parseDate(d[0])); | |
}); | |
//axis | |
var xScale= d3 | |
.scaleTime() | |
.domain(d3.extent(resultData, d=>d[0])) | |
.range([0, w]); | |
var yScale = d3 | |
.scaleLinear() | |
.domain(d3.extent(resultData, d=>d[1])) | |
.range([h,0]); | |
//add area | |
area = d3.area() | |
.x(d=>xScale(d[0])) | |
.y0(function() { return yScale.range()[0]; }) | |
//this is important, it's not 0, it's like h | |
.y1(d=>yScale(d[1])); | |
svg | |
.append("path") | |
.datum(resultData) | |
.attr("class", "area") | |
.attr("d", area); | |
svg.append("g") | |
.attr("class", "axis") | |
.attr("transform", "translate(2," + (h+2) + ")") | |
.call(d3.axisBottom(xScale) | |
.ticks(10))//.tickFormat(d3.timeFormat("%Y-%b-%d"))) | |
.selectAll("text") | |
.style("text-anchor", "end") | |
.attr("dx", "-.8em") | |
.attr("dy", ".15em") | |
.attr("transform", "rotate(-65)"); | |
//.tickFormat(d3.timeFormat("%Y"))); | |
svg.append("g") | |
.attr("class", "axis") | |
.call(d3.axisLeft(yScale) | |
.ticks(10)) | |
.append("text") | |
.attr("y", 6) | |
.attr("dy", ".71em") | |
.style("text-anchor", "end") | |
.text("GDP"); }); | |
</script> | |
</body> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment