Public
Edited
Apr 6, 2023
Insert cell
Insert cell
Insert cell
//This section creates the map
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append(legend)
.attr("transform", "translate(85,70)"); //this is where we can move the legend to make sure it is not behind the map, here I have moved it to the top left and moved the map down and to the right a bit as it is a bit awkard to fit both on the canvas because of the state being so close to a square.

svg.append("g")
.selectAll("path")
.data(topojson.feature(polygons, polygons.objects.counties_topojson).features)
.join("path")
.attr("stroke", "black") //can change the color lines around the counties, here I changed it to black
.attr("fill", d => color(data.get(d.properties[idAttribute])))
.attr("d", path)
.append("title")
.text(d => `${d.properties[idAttribute]}, ${format(data.get(d.properties[idAttribute]))}`);
//this is how to get the values displayed when you hover over each county, also gives us info for if that county is low or high for either variable

return svg.node();
}
Insert cell
Insert cell
// http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/

//To add a new color bivariate color scheme you could just change the name: and the hexcodes for the colors:. while there is no rule to use specific colors to create a useful and visual good looking map you would want to use something like a continuoius color scheme going from light to dark, this would work for unipolar variables but if they were bipolar you could use a diverging color scheme. The example from this map and the "BuPu" color scheme shows the low-low variables starting at the lightest color and as it moves to high-high contiunes to get darker and darker

//this is where the colors are defined for the 4 different color schemes available to us. In each color scheme there is 9 different defined colors
schemes = [
{
name: "RdBu",
colors: [
"#e8e8e8", "#e4acac", "#c85a5a",
"#b0d5df", "#ad9ea5", "#985356",
"#64acbe", "#627f8c", "#574249"
]
},
{
name: "BuPu",
colors: [
"#e8e8e8", "#ace4e4", "#5ac8c8",
"#dfb0d6", "#a5add3", "#5698b9",
"#be64ac", "#8c62aa", "#3b4994"
]
},
{
name: "GnBu",
colors: [
"#e8e8e8", "#b5c0da", "#6c83b5",
"#b8d6be", "#90b2b3", "#567994",
"#73ae80", "#5a9178", "#2a5a5b"
]
},
{
name: "PuOr",
colors: [
"#e8e8e8", "#e4d9ac", "#c8b35a",
"#cbb8d7", "#c8ada0", "#af8e53",
"#9972af", "#976b82", "#804d36"
]
}
]
Insert cell
labels = ["low", "", "high"]
Insert cell
n = Math.floor(Math.sqrt(colors.length))
Insert cell
x = d3.scaleQuantile(Array.from(data.values(), d => d[0]), d3.range(n))
//creates a scale of low, medium or high for each variable, here for X below for Y
Insert cell
y = d3.scaleQuantile(Array.from(data.values(), d => d[1]), d3.range(n))
Insert cell
path = d3.geoPath().projection(projection)
Insert cell
//Rotate the map sets the longitude of origin for our UTM projection.
projection = d3.geoTransverseMercator().rotate([105,0]).fitExtent([[150, 50], [width, height]], polygon_features)
Insert cell
polygon_features = topojson.feature(polygons, polygons.objects.counties_topojson)
Insert cell
data = Object.assign(new Map(d3.csvParse(await FileAttachment("counties_colorado.csv").text(), ({geonum, white_nh, per_cap_in, pop}) => [+geonum, [100*+white_nh/pop, +per_cap_in]])), {title: ["% White", " Income Per Capita"]})
//this is where we can join the topojson to the csv by using the idAttribute to join the geometries to the attributes

//also here we can create the standardized variable such as, [100*+white_nh/pop] and to assing the titles for the legend being % white and Income Per

Insert cell
idAttribute = "geonum"
//this is the attribute we use to join them together, in this case "geonum"
Insert cell
polygons = FileAttachment("geo_export.json").json()
Insert cell
height = 610
Insert cell
width = 875
Insert cell
//this section used to create the legend
legend = () => {
const k = 24;
const arrow = DOM.uid();
return svg`<g font-family=sans-serif font-size=10>
<g transform="translate(-${k * n / 2},-${k * n / 2}) rotate(-45 ${k * n / 2},${k * n / 2})">
<marker id="${arrow.id}" markerHeight=10 markerWidth=10 refX=6 refY=3 orient=auto>
<path d="M0,0L9,3L0,6Z" />
</marker>
${d3.cross(d3.range(n), d3.range(n)).map(([i, j]) => svg`<rect width=${k} height=${k} x=${i * k} y=${(n - 1 - j) * k} fill=${colors[j * n + i]}>
<title>${data.title[0]}${labels[j] && ` (${labels[j]})`}
${data.title[1]}${labels[i] && ` (${labels[i]})`}</title>
</rect>`)}
<line marker-end="${arrow}" x1=0 x2=${n * k} y1=${n * k} y2=${n * k} stroke=black stroke-width=1.5 />
<line marker-end="${arrow}" y2=0 y1=${n * k} stroke=black stroke-width=1.5 />
<text font-weight="bold" dy="0.71em" transform="rotate(90) translate(${n / 2 * k},6)" text-anchor="middle">${data.title[0]}</text>
<text font-weight="bold" dy="0.71em" transform="translate(${n / 2 * k},${n * k + 6})" text-anchor="middle">${data.title[1]}</text>
</g>
</g>`;
}
Insert cell
color = {
return value => {
if (!value) return "#ccc";
let [a, b] = value;
return colors[y(b) + x(a) * n];
};
}
Insert cell
formatNum = d3.format(".1f")
Insert cell
format = (value) => {
if (!value) return "N/A";
let [a, b] = value;
return `${a} ${data.title[0]}${labels[x(a)] && ` (${labels[x(a)]})`}
${formatNum(b)} ${data.title[1]}${labels[y(b)] && ` (${labels[y(b)]})`}`;
}
Insert cell
topojson = require("topojson-client@3")
Insert cell
d3 = require("d3@5")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more