Skip to content

Instantly share code, notes, and snippets.

@vasturiano
Last active October 25, 2018 11:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vasturiano/62e0bf2a189a6cd040846d379f9303d1 to your computer and use it in GitHub Desktop.
Save vasturiano/62e0bf2a189a6cd040846d379f9303d1 to your computer and use it in GitHub Desktop.
World cartogram on d3 v4
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.5/dat.gui.js"></script>
<script src="//unpkg.com/cartogram-chart@1"></script>
<script src="//unpkg.com/d3-scale-chromatic"></script>
<style>body { margin: 0; }</style>
</head>
<body>
<div id="world"></div>
<script>
// Controls
const gui = new dat.GUI();
const colorScale = d3.scaleSequential(d3.interpolateYlOrBr);
const cartogram = Cartogram()
.valFormatter(n => n.toPrecision(3))
(document.getElementById('world'));
d3.json('.ne_110m_admin_0_countries.json', (error, world) => {
if (error) throw error;
// exclude antarctica
world.objects.countries.geometries.splice(
world.objects.countries.geometries.findIndex(d => d.properties.ISO_A2 === 'AQ'),
1
);
let ccData;
cartogram
.topoJson(world)
.topoObjectName('countries')
.value(({ properties: { ISO_A2 } }) => ccData[ISO_A2])
.color(({ properties: { ISO_A2 } }) => colorScale(ccData[ISO_A2]))
.label(({ properties: p }) => `${p.NAME} (${p.ISO_A2})`)
.onClick(d => console.info(d));
const controls = { 'Iterations': 15, 'Randomize': () => { genVals(); render(); }};
gui.add(controls, 'Iterations', 1, 40).step(1).onChange(render);
gui.add(controls, 'Randomize');
genVals();
render();
//
function genVals() {
ccData = Object.assign(...world.objects.countries.geometries
.map(({ properties: { ISO_A2 } }) => ({ [ISO_A2]: Math.random() }))
);
}
function render() {
cartogram.iterations(controls.Iterations);
}
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment