Credit
I started with this bubble chart from d3 in depth and I used the marvel data from this block
should be cool but not as cool as stamen
Built with blockbuilder.org
xxxxxxxxxx
<!-- <!DOCTYPE html> -->
<meta charset="utf-8">
<head>
<title>Force layout (foci)</title>
</head>
<style>
</style>
<body>
<div id="content">
<svg width="1000" height="500">
<g transform="translate(50, 200)"></g>
</svg>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>
<script>
const width = 1000, height = 500;
const centerX = Math.floor(width / 2);
const colorScale = ['orange', 'lightblue', '#B19CD9'];
const xCenter = [150, 400, 650]
const handleLoadComplete = (heroes) => {
//const answers = heroes[0].children.length;
const centerChild = Math.floor(heroes.length/2)
// center node should be huge and only 1 of them
const nodes = heroes.map(function(d, i) {
return {
radius: (i === centerChild) ? 150 : 50,
category: (i === centerChild) ? 1 : (i < centerChild) ? 0 : 2,
profile: (i === centerChild) ? true : false,
img: d.img,
}
});
function ticked() {
const images = d3.select('svg g')
.selectAll('g')
.data(nodes);
function getX(d,i) {
if (d.profile) {
return d.radius - 280;
} else if ( i > 4) {
return d.radius - 220
} else {
return d.radius;
}
}
images.enter()
.append('g')
.append("svg:image")
.attr("xlink:href", function(d) { return d.img;})
.attr("x", function(d,i) { return getX(d,i)})
.attr("y", function(d, i) { return -d.radius })
.attr("height", function(d) { return d.radius * 2})
.attr("width", function(d) { return d.radius * 2})
.merge(images)
.attr("transform", (d,i) => {
return "translate(" + (d.x - 10) + "," + (d.y - 10) + ")"});
const u = d3.select('svg g')
.selectAll('circle')
.data(nodes);
const enter = u.enter()
.append('circle')
.attr('r', function(d) {
return d.radius;
})
.style('fill', function(d) {
return colorScale[d.category];
})
.style('fill', "none")
.merge(u)
.attr('cx', function(d) {
return d.x;
})
.attr('cy', function(d) {
return d.y;
});
enter.append('g').append("svg:image")
.attr("xlink:href", function(d) { return d.img;})
.attr("x", function(d) { return -25;})
.attr("y", function(d) { return -25;})
.attr("height", 50)
.attr("width", 50);
u.exit().remove();
}
const forceX = d3.forceX(width / 2).strength(0.015)
const forceY = d3.forceY(height / 5).strength(0.015)
const simulation = d3.forceSimulation(nodes)
.force('charge', d3.forceManyBody().strength(5))
//.force('gravity',0.5)
.force('x', d3.forceX().x(function(d) {
return xCenter[d.category];
}))
.force('y', forceY)
.force('collision', d3.forceCollide().radius(function(d) {
return d.radius;
}))
.on('tick', ticked);
}
d3.json("marvel.json").then(
response => {
const children = response.children;
const heroes = children.filter(child => child.name === "Heroes")[0].children;
console.log("heroes", heroes )
handleLoadComplete(heroes);
},
error => {},
)
</script>
</body>
</html>
https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js