A response to a query on D3JS Slack (https://d3js.slack.com/archives/C07EVSL59/p1498059093072467)
Built with blockbuilder.org
license: mit |
A response to a query on D3JS Slack (https://d3js.slack.com/archives/C07EVSL59/p1498059093072467)
Built with blockbuilder.org
<!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; | |
} | |
circle { | |
fill: tomato | |
} | |
</style> | |
</head> | |
<body> | |
<script> | |
let w = 300, | |
h = 400; | |
let dataset = [2.3, 5.2, 2.8, 0.31, 0.41, 12, 0.064, 15, 0.033, 13, 17, 0.034, 14, 0.23, 18, 13, 14, 0.049, 0.038]; | |
dataset = dataset.sort(d3.descending); | |
let offset = 0; | |
let padding = 2 | |
let stackedData = [] | |
dataset.forEach(function (d, i) { | |
let datum = {}; | |
datum.id = i; | |
datum.value = d; | |
datum.sqrtValue = Math.sqrt(d); //radius will be based on this | |
offset = offset + Math.sqrt(d) + padding; //set the cy offset down by padding + radius of this circle | |
datum.offset = offset; //record offset, ie centre of this circle | |
offset = offset + Math.sqrt(d); //move offset again to bottom of this circle | |
stackedData.push(datum); | |
}); | |
console.log(stackedData); | |
offset = offset + padding; //add last bit of padding, before using for scales | |
let yScale = d3.scaleLinear() | |
.domain([0, offset]) | |
.range([0, h]); | |
let rScale = d3.scaleLinear() | |
.domain([0, offset]) | |
.range([0, h]); | |
let svg = d3.select('body') | |
.append('svg') | |
.attr('width', w) | |
.attr('height', h); | |
let circles = svg.selectAll('circle') | |
.data(stackedData) | |
.enter() | |
.append('circle') | |
.attr('cx', w / 2) | |
.attr('cy', function (d) { | |
return yScale(d.offset); | |
}) | |
.attr('r', function (d) { | |
return rScale(d.sqrtValue); | |
}) | |
.attr("fill", function (d) { | |
return "rgb(0, 0, " + Math.round((d * 20)) + ")"; | |
}); | |
</script> | |
</body> |