Published
Edited
Dec 7, 2021
Insert cell
Insert cell
Insert cell
countries = FileAttachment("custom.geo-3.json").json()
Insert cell
northAmerica = ({
type: "FeatureCollection",
features: countries.features
.filter((d) => d.properties.continent == "North America")
.filter((d) => d.properties.name != "United States")
})
Insert cell
states = FileAttachment("gz_2010_us_040_00_5m.json").json()
Insert cell
Insert cell
//for converting long-lat to pixels
projection = d3.geoAlbers().center([-10, 50]).scale(400)
//center on the Americas
//.rotate([90, -15, 0])
Insert cell
height = 600
Insert cell
Insert cell
elSalvador = FileAttachment("El Salvador.csv").csv()
Insert cell
mexico = FileAttachment("Mexico.csv").csv()
Insert cell
guatemala = FileAttachment("Guatemala.csv").csv()
Insert cell
Insert cell
//Create an empty array, and combine (concatenate) all migration data together into it
migrationData = [].concat(elSalvador, mexico, guatemala)
Insert cell
//Find unique source countries from concatenated array
supportedSources = Array.from(new Set(migrationData.map((d) => d.Hometown)))
Insert cell
supportedGeoData = supportedSources.map((d) =>
countries.features.find((e) => e.properties.name == d)
)
Insert cell
//Find all different column headers from first row in CSV file, and then remove the two that aren't time-related
supportedYears = Object.keys(migrationData[0])
.filter((d) => d != "Hometown")
.filter((d) => d != "Destination")
Insert cell
Insert cell
statesWithMigrationData = ({
type: "FeatureCollection",
features: states.features
.map((state) => {
return {
...state,
migration: migrationData.filter(
(d) => d.Destination == state.properties.NAME
)
};
})
.map((state) => ({
...state,
centroid: d3.geoCentroid(state),

trails: supportedGeoData.map((country) => ({
type: "Feature",
properties: {
source: country.properties.name,
target: state.properties.NAME,
migration: migrationData
.filter((d) => d.Destination == state.properties.NAME)
.filter((d) => d.Hometown == country.properties.name)[0],
distance: d3.geoDistance(
d3.geoCentroid(state),
d3.geoCentroid(country)
)
},
geometry: {
type: "LineString",
coordinates: [d3.geoCentroid(country), d3.geoCentroid(state)]
}
}))
}))
})
Insert cell
parseInt(
statesWithMigrationData.features[0].migration.filter(
(d) => d.Hometown == "Mexico"
)[0]["2010"]
)
Insert cell
Insert cell
migrationScale = d3
.scaleLinear()
.domain(
d3.extent(
migrationData.filter((d) => selectedSources.includes(d.Hometown)),
(d) => parseInt(d[selectedPeriod])
)
)
.range([0, 1])
Insert cell
//show min and maxes to ensure everything is working
d3.extent(
migrationData.filter((d) => selectedSources.includes(d.Hometown)),
(d) => parseInt(d[selectedPeriod])
)
Insert cell
Insert cell
//Create some buttons for each source country
viewof selectedSources = Inputs.checkbox(supportedSources, {
value: ["El Salvador", "Mexico", "Guatemala"]
})
Insert cell
//Create some buttons for each column from CSV file
viewof selectedPeriod = Inputs.radio(supportedYears, { value: "2010" })
Insert cell
Insert cell
Insert cell
Insert cell
//To read about what's happening here...
//https://observablehq.com/@observablehq/introduction-to-generators
{
while (animated == true) {
for (const year of supportedYears) {
viewof selectedPeriod.value = year;
viewof selectedPeriod.dispatchEvent(new Event("input"));
yield Promises.delay(5000);
}
}
}
Insert cell
sourceScale = d3.scalePoint().domain(supportedSources).range([0, 1])
Insert cell
targetScale = d3
.scalePoint()
.domain(states.features.map((d) => d.properties.NAME))
.range([0, 1])
Insert cell
activeMigrationValues = migrationData
.filter((d) => selectedSources.includes(d.Hometown))
.map((d) => d[selectedPeriod])
.map((d) => parseInt(d))
Insert cell
//for how many seconds the animaton will take, based on population
durationScale = d3.scaleLinear().domain(activeMigrationValues).range([20, 10])
Insert cell
{
//svg area
const svg = d3.create("svg").attr("width", width).attr("height", height);
svg
.append("rect")
.attr("width", width)
.attr("height", height)
.attr("fill", "#555b6e");

//rotated group to hold countries
const g = svg.append("g");
// .attr("transform", "rotate(-90," + width / 2 + "," + height / 2 + ")");

//the function that takes geographic data and converts to SVG paths
const path = d3.geoPath().projection(projection);

//draw countries
g.selectAll(".countries")
.data(northAmerica.features)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", (d) =>
supportedSources.includes(d.properties.name) ? "white" : "#bee3db"
)
.attr("fill", (d) =>
selectedSources.includes(d.properties.name)
? d3.interpolatePlasma(sourceScale(d.properties.name))
: "#89b0ae"
)
.attr("stroke-width", 1);

//draw countries
g.selectAll(".states")
.data(statesWithMigrationData.features)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "#bee3db")
.attr("stroke-width", 1)
.attr("fill", "#89b0ae");

//walk through states
for (let state of statesWithMigrationData.features) {
const stateArcs = state.trails
.filter((d) => selectedSources.includes(d.properties.source))
.filter((d) => d.properties.migration);

//draw arcs
g.selectAll(".arcs")
.data(stateArcs)
.enter()
.append("path")
.attr("d", (d) => path(d))
.attr("fill", "none")
.attr("stroke-width", 2)
.attr("stroke", (d) =>
d3.interpolatePlasma(sourceScale(d.properties.source))
)
.style("stroke-dasharray", "2 20")
.style("stroke-dashoffset", (d) => Math.random() * 100)
.style(
"animation",
(d) =>
"dash " +
durationScale(parseInt(d.properties.migration[selectedPeriod])) +
"s linear infinite"
);
}

return svg.node();
}
Insert cell
Insert cell
html`
<style>
@keyframes dash {
to {
stroke-dashoffset: -100;
}
}
</style>`
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