Data Visualisation with a Choropleth Map
Posted on: August 11, 2023
This FreeCodeCamp data visualisation project is to create a choropleth map as this. Unlike the previous three data visualisation projects, this project is creating something that is not taught in the previous exercises and I have learned a few new knowledge from this project.
Fetch JSON Data
FreeCodeCamp has talked about two different methods for fetching JSON data. One is using JavaScript XMLHttpRequest:
const req = new XMLHttpRequest();req.open('GET', url, true)req.onload = () => {dataset = JSON.parse(req.responseText)}req.send()
But I prefer using JavaScript fetch method because it looks cleaner:
fetch(url).then(response => response.json()).then(data => dataset = data)
While researching and reading d3 documentation, I found out d3 has provided a fucntion to fetch JSON file: d3.json()
and it looks even more cleaner.
d3.json(url).then(data => dataset = data)
TopoJSON
The retrieved data is in TypoJSON format which is to encode topology, and we need the arcs field as data for creating svg path but d3 does not support this format. Therefore we need to convert the data into GeoJSON using topojson.feature()
.
d3.json(countyURL).then((data) => {// We only want the data within features partcountyDataset = topojson.feature(data, data.objects.counties).features;});
D3 Color Schemes
D3 has provided some color schemes which is very useful when you need a range of colors, including sequential, diverging and categorical colors. Most importantly it works with d3 scales.
const colorScale = d3.scaleThreshold().domain(d3.range(min, max, (max - min) / 8)).range(d3.schemeGreens[9]);
This method helps me to create a scale for the legend box, so it looks different to the hard coded legend box to the previous three projects.