Published
Edited
Feb 12, 2022
1 star
Insert cell
md`# Cost of Living Index by State`


Insert cell
Insert cell
**Data Source:** https://worldpopulationreview.com/state-rankings/cost-of-living-index-by-state
Insert cell
md`**Note:** Instead of placing the mean value in the middle of the color scale, median was used.

This was done because some states like Hawaii had a cost of living index far above the other states, which skews the mean. That would have resulted in a map with mostly green states because most states have a cost of living index far below Hawaii's.

By using the median for the color scale, we can more easily distinguish the relative cost differences between the states.`
Insert cell
mapColors = ["green", "yellow", "red"]
Insert cell
legend = Legend(d3.scaleDiverging(costDomain, mapColors), {
title: "Cost of Living Index",
ticks: 10
})
Insert cell
Insert cell
import {Legend} from "@d3/color-legend"

Insert cell
geojson = FileAttachment("usState.json").json()
Insert cell
costRaw = FileAttachment("csvData.csv").csv()
Insert cell
Insert cell
costData = costRaw.map(stateObj => {
return {
state: stateObj.State,
cost: +stateObj.costIndex.slice(0,4)
}
})
Insert cell
Insert cell
Insert cell
Insert cell
margin = ({
top: 30,
left: 50,
right: 50,
bottom: 60
});
Insert cell
allCostIdx = costData.map(d => d.cost)
Insert cell
costDomain = [d3.min(allCostIdx),
d3.median(allCostIdx),
d3.max(allCostIdx)]
Insert cell
colorScale = d3.scaleLinear()
.domain(costDomain)
.range(mapColors)
Insert cell
Insert cell
projection = d3.geoAlbersUsa()
.fitSize([
width - margin.left - margin.right,
height - margin.top - margin.bottom
], geojson)
Insert cell
pathGen = d3.geoPath(projection)
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);

const states = svg.selectAll("path.states")
.data(geojson.features, d => d.properties.NAME)
.join("path")
.attr("class", "states")
.attr("d", d => pathGen(d))
.attr("fill", d => ["District of Columbia", "Puerto Rico"]
.includes(d.properties.NAME)
? "Black"
: colorScale(costData.filter(obj => obj.state === d.properties.NAME)[0].cost))
.attr("stroke", "black")

return svg.node();
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more