Built with blockbuilder.org
Last active
June 29, 2017 04:29
-
-
Save seemantk/b71ee07f66d90d0ec8c42d741e13a050 to your computer and use it in GitHub Desktop.
Carrots & Pens
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> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<script> | |
// Feel free to change or delete any of the code you see in this editor! | |
var svg = d3.select("body").append("svg") | |
.attr("width", 960) | |
.attr("height", 500) | |
; | |
var margin = { | |
top: 20, | |
bottom: 20, | |
left: 20, | |
right: 20 | |
} | |
var data = [ | |
{ name: "andrew", pens: 5, carrots: 50, phones: 1 } | |
, { name: "avra", pens: 0, carrots: 25, phones: 1} | |
, { name: "dana", pens: 3, carrots: 8, phones: 2} | |
, { name: "elaine", pens: 8, carrots: 1, phones: 1} | |
, { name: "kyle", pens: 20, carrots: 0, phones: 0} | |
, { name: "megan", pens: 20, carrots: 22, phones: 8} | |
, { name: "nam", pens: 20, carrots: 14, phones: 0} | |
, { name: "naoya", pens: 15, carrots: 18, phones: 14} | |
, { name: "patience", pens: 6, carrots: 3, phones: 89} | |
, { name: "virginia", pens: 4, carrots: 18, phones: 2} | |
] | |
var xScale = d3.scaleBand() | |
.domain(data.map(function(d){ | |
return d.name | |
})) | |
.range([margin.left, 960-margin.left - margin.right]) | |
//console.log(xScale.domain(),xScale.range()) | |
var yExtent = d3.extent(data,function(d){return d.pens +d.carrots +d.phones | |
}) | |
var yScale = d3.scaleLinear() | |
.domain(yExtent) | |
.range([margin.bottom, 500-margin.top-margin.bottom]) | |
//console.log(yExtent) | |
var stack = d3.stack() | |
.keys(["pens", "carrots", "phones"]) | |
.order(d3.stackOrderNone) | |
.offset(d3.stackOffsetNone); | |
//console.log(stack(data)) | |
var groups = svg.selectAll("g") | |
.data(stack(data)) | |
.enter() | |
.append("g") | |
var rects = groups.selectAll("rect") | |
.data(function(d) {return d | |
}) | |
.enter() | |
.append("rect") | |
.attr("x", function(d){ return xScale(d.data.name) | |
}) | |
.attr("y", function(d) { return yScale(d[0]) | |
}) | |
.attr("width", xScale.bandwidth()) | |
.attr("height", function(d){ return yScale(d[1]) | |
}) | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment