This example shows how d3.nest and d3.layout.stack can be used in conjunction. This forms the basis for a stacked bar chart. This is example 16 from the screencast Splitting Charts.
MIT License
This example shows how d3.nest and d3.layout.stack can be used in conjunction. This forms the basis for a stacked bar chart. This is example 16 from the screencast Splitting Charts.
MIT License
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>D3 Example</title> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
</head> | |
<body> | |
<script> | |
var layerColumn = "religion"; | |
var yColumn = "population"; | |
var xColumn = "country"; | |
function render(data){ | |
var nested = d3.nest() | |
.key(function (d){ return d[layerColumn]; }) | |
.entries(data); | |
var stack = d3.layout.stack() | |
.y(function (d){ return d[yColumn]; }) | |
.values(function (d){ return d.values; }); | |
var layers = stack(nested); | |
d3.select("body").append("pre") | |
.text(JSON.stringify(layers, null, 2)); | |
} | |
function type(d){ | |
d.population = +d.population; | |
return d; | |
} | |
d3.csv("religionByCountryTop5.csv", type, render); | |
</script> | |
</body> | |
</html> |
country | religion | population | |
---|---|---|---|
China | Christian | 68410000 | |
China | Muslim | 24690000 | |
China | Unaffiliated | 700680000 | |
China | Hindu | 20000 | |
China | Buddhist | 244130000 | |
China | Folk Religions | 294320000 | |
China | Other Religions | 9080000 | |
China | Jewish | 0 | |
India | Christian | 31130000 | |
India | Muslim | 176190000 | |
India | Unaffiliated | 870000 | |
India | Hindu | 973750000 | |
India | Buddhist | 9250000 | |
India | Folk Religions | 5840000 | |
India | Other Religions | 27560000 | |
India | Jewish | 10000 | |
USA | Christian | 243060000 | |
USA | Muslim | 2770000 | |
USA | Unaffiliated | 50980000 | |
USA | Hindu | 1790000 | |
USA | Buddhist | 3570000 | |
USA | Folk Religions | 630000 | |
USA | Other Religions | 1900000 | |
USA | Jewish | 5690000 | |
Indonesia | Christian | 23660000 | |
Indonesia | Muslim | 209120000 | |
Indonesia | Unaffiliated | 240000 | |
Indonesia | Hindu | 4050000 | |
Indonesia | Buddhist | 1720000 | |
Indonesia | Folk Religions | 750000 | |
Indonesia | Other Religions | 340000 | |
Indonesia | Jewish | 0 | |
Brazil | Christian | 173300000 | |
Brazil | Muslim | 40000 | |
Brazil | Unaffiliated | 15410000 | |
Brazil | Hindu | 0 | |
Brazil | Buddhist | 250000 | |
Brazil | Folk Religions | 5540000 | |
Brazil | Other Religions | 300000 | |
Brazil | Jewish | 110000 |