Test driving d3-cartogram on D3 v4 using the cartogram-chart web component.
Last active
October 25, 2018 11:06
-
-
Save vasturiano/62e0bf2a189a6cd040846d379f9303d1 to your computer and use it in GitHub Desktop.
World cartogram on d3 v4
This file contains hidden or 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
<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