Public
Edited
May 15, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
ldn = computedPopns.filter(row => row.city == 'London')[0];
Insert cell
ldn['urban_2050_a'] > ldn['urban_2019']
Insert cell
computedPopns
Insert cell
allCities = {
//worldMap.attr("style", "background-color:#23548A;");
worldMap.select("#cities").remove()
worldMap.select("#names").remove()
// worldMap.select("#land").attr("fill", "#d8d8d8");

const simulation = d3
.forceSimulation(computedPopns)
.force(
"x",
d3.forceX((d) => mapProjection([d.Longitude, d.Latitude])[0])
)
.force(
"y",
d3.forceY((d) => mapProjection([d.Longitude, d.Latitude])[1])
)
// .force(
// "collide", d =>
// d3.forceCollide(radius*repulsionFactor).strength(0.5)
// )

.force(
"collide",
d3.forceCollide(d => {
if (show === 'GDP') {
if (d[gdp[0]] < d[gdp[1]]) {
return gdpScale(d[gdp[0]])+repulsionFactor;
} else {
return gdpScale(d[gdp[1]])+repulsionFactor;
}
} else {
if (d[popn[0]] < d[popn[1]]) {
return popnScale(d[popn[0]])+repulsionFactor;
} else {
return popnScale(d[popn[1]])+repulsionFactor;
}
}
}).strength(1)
);

const nodeG = worldMap.append("g")
.attr("id", "cities")
.selectAll("g")
.data(computedPopns)
.join("g")
.call(drag(simulation));

// nodeG.append('circle')
// .attr("r", d => radiusScale(d[d["plotOrder"][2]]));

// nodeG.append("g")
// .each(function(node) {
// for (let i in node["plotOrder"]) {
// let year = node["plotOrder"][i];
// d3.select(this).append("g")
// .append("circle")
// .attr("r", d => radiusScale(d[year]))
// .attr("fill", yearScale(year));
// }
// })

if (show==="Comparison"){
nodeG.append('circle')
.attr("r", radius)//(d) => radiusScale(d[d["plotOrder"][0]])
.attr("fill", "none");
nodeG.append("g")
.each(function(node, i) {
let symbol = d3.select(this).append("g");
let pPlotOrder = node['popnPlotOrder'];
let gPlotOrder = node['gdpPlotOrder'];
symbol.append("clipPath")
.attr("id", "left-clip_" + i)
.append("rect")
.attr("width", radius)
.attr("height", radius * 2)
.attr("x", -radius)
.attr("y", -radius);
for (let i = 0; i < pPlotOrder.length; i+=1) {
let prop = pPlotOrder[i];
symbol
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", d => popnScale(d[prop]))
.attr("clip-path", "url(#left-clip_" + i + ")")
.style("fill", (d) => pColor[prop]);
}
symbol.append("clipPath")
.attr("id", "right-clip_" + i)
.append("rect")
.attr("width", radius)
.attr("height", radius * 2)
.attr("x", 0)
.attr("y", -radius);
for (let i = 0; i < gPlotOrder.length; i+=1) {
let prop = gPlotOrder[i];
symbol
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", d => gdpScale(d[prop]))
.attr("clip-path", "url(#right-clip_" + i + ")")
.style("fill", gColor[prop]);
}
})
} else {
let nodeProp;
let nodeScale;
let nodeColor;
if (show==="GDP") {
nodeProp = 'gdpPlotOrder';
nodeScale = gdpScale;
nodeColor = gColor;
} else {
nodeProp = 'popnPlotOrder';
nodeScale = popnScale;
nodeColor = pColor;
}
nodeG.append("g")
.each(function(node, i) {
let symbol = d3.select(this).append("g");
// let pPlotOrder = node['popnPlotOrder'];

if (showType === "Both") {
let plotOrder = node[nodeProp];
for (let i = 0; i < plotOrder.length; i+=1) {
let prop = plotOrder[i];
symbol
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", d => nodeScale(d[prop]))
.attr("clip-path", "url(#right-clip_" + i + ")")
.style("fill", nodeColor[prop]);
}
} else {
if (show === "GDP") {
let prop = showType === 2019 ? "gdp_urban_2019" : "gdp_urban_2050_a";
symbol
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", d => nodeScale(d[prop]))
.attr("clip-path", "url(#right-clip_" + i + ")")
.attr("stroke", "white")
.attr("stroke-width", "0.5px")
.style("fill", nodeColor[prop]);
} else {
let prop = showType === 2019 ? "urban_2019" : "urban_2050_a";
symbol
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", d => nodeScale(d[prop]))
.attr("clip-path", "url(#right-clip_" + i + ")")
.attr("stroke", "white")
.attr("stroke-width", "0.5px")
.style("fill", nodeColor[prop]);

}
}
})
}

simulation.on("tick", () => {
nodeG.attr("transform", d => `translate(${d.x}, ${d.y})`)});
invalidation.then(() => simulation.stop());

// worldMap.append("g")
// .attr("id", "names")
// .selectAll("text")
// .data(topCities)
// .join("text")
// .attr("transform", d => `translate(${mapProjection([d["Longitude"], d["Latitude"]])})`)
// .attr("font-size", "0.4em")
// .attr("font-family", "Akkurat LL")
// .attr("fill", "white")
// .attr("stroke", "#063249")
// .attr("stroke-width", "0.1px")
// .attr("paint-order", "stroke")
// .text(d => d["Urban Agglomeration"]);
return worldMap.node();
}
Insert cell
function forceClusterCollision() {
let nodes
let radii
let strength = 1
let iterations = 1
let clusterPadding = 0 //addition

function radius(d) { return d.r }
function x(d) { return d.x + d.vx }
function y(d) { return d.y + d.vy }
function constant(x) { return function() { return x } }
function jiggle() { return 1e-6 } //change - PLEASE no Math.random() in there ಥ﹏ಥ
// function jiggle() { return (Math.random() - 0.5) * 1e-6 }

function force() {
let i
let n = nodes.length
let tree
let node
let xi
let yi
let ri
let ri2

for (let k = 0; k < iterations; ++k) {
tree = d3.quadtree(nodes, x, y).visitAfter(prepare)
for (i = 0; i < n; ++i) {
node = nodes[i]
ri = radii[node.index]
ri2 = ri * ri
xi = node.x + node.vx
yi = node.y + node.vy
tree.visit(apply)
}//for i
}//for k

function apply(quad, x0, y0, x1, y1) {
let data = quad.data
let rj = quad.r
let r = ri + rj + clusterPadding //change
if (data) {
if (data.index > node.index) {
let x = xi - data.x - data.vx
let y = yi - data.y - data.vy
let l = x * x + y * y
r = ri + rj + (node.cluster !== quad.data.cluster ? clusterPadding : 0) //addition

if (l < r * r) {
if (x === 0) x = jiggle(), l += x * x
if (y === 0) y = jiggle(), l += y * y
l = (r - (l = Math.sqrt(l))) / l * strength
node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj))
node.vy += (y *= l) * r
data.vx -= x * (r = 1 - r)
data.vy -= y * r
}//if
}//if
return
}//if
return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r
}//apply
}//force

function prepare(quad) {
if (quad.data) return quad.r = radii[quad.data.index];
for (let i = quad.r = 0; i < 4; ++i) {
if (quad[i] && quad[i].r > quad.r) {
quad.r = quad[i].r
}//if
}//for i
}

function initialize() {
if (!nodes) return;
let i, n = nodes.length, node
radii = new Array(n)
for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes)
}

force.initialize = function (_) {
nodes = _
initialize()
return force
}

force.iterations = function (_) {
return arguments.length ? (iterations = +_, force) : iterations
}

//I wish strength could be a function of the node as well...
force.strength = function (_) {
return arguments.length ? (strength = +_, force) : strength
}

force.radius = function (_) {
return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), force) : radius
}
//addition - the actual pixels of padding
force.clusterPadding = function (_) {
return arguments.length ? (clusterPadding = +_, force) : clusterPadding
}

return force
}//function forceCollision
Insert cell
Insert cell
popn = ['urban_2019', 'urban_2050_c']
Insert cell
gdp = ['gdp_urban_2019', 'gdp_urban_2050_c']
Insert cell
selectedPopns[0]
Insert cell
Insert cell
d3
.select(test)
.select('[aria-description="GDP per capita (USD) →"]')
.enter()
.selectAll("text")
.each(function (d) {
// d is the tick's value (in this case, a number)
d3.select(this)
.attr('font-family', 'Helvetica Neue')
.attr("fill", 'black')
.attr("font-size", 10);
})
Insert cell
test2 = Plot.plot({
inset: 8,
grid: true,
width: width*1.25,
height: 1000,
marginLeft: 50, // space to the left of the chart
marginBottom: 50, // space below the chart
color: {
legend: true,
},
facet: {
data: baseData,
x: "continent"
},
x: {
// label: "GDP per capita (USD) →",
tickFormat: "~s",
type: "log",
ticks: 3
},
y: {
// label: "↑ Population (people)",
type: "log",
tickFormat: "~s",
// textColor: "white",
ticks: 5
},
marks: [
//dots
// Plot.dot(baseData, {x: "gdp_capita_2019", y: "urban_2019", text: "iso3", stroke: "continent", strokeWidth: 1,
// //fill:"white", r: 10}),
// }),
// Plot.dot(data_gdpc, {x: "gdp_capita_2050", y: "urban_2050_a", text: "iso3", stroke: "continent"}),
//links
Plot.link(baseData, {
x1: "gdp_capita_2019",
y1: "urban_2019",
x2: "gdp_capita_2050",
y2: "urban_2050_a",
stroke: "continent",
markerEnd: "arrow",
opacity: 0.4,
strokeWidth: 2,
}),
//text
Plot.text(baseData.slice(0, 150), {x: "gdp_capita_2019", y: "urban_2019", text: "city",
fill: "continent",
stroke: "white",
opacity: 0.8,
fontSize: 12}),
// Plot.text(baseData, {x: "gdp_capita_2050", y: "urban_2050_a", text: "city",
// fill: "continent",
// // stroke: "white",
// opacity: 0.8,
// fontSize: 11}),
]
})
Insert cell
test3 = Plot.plot({
inset: 8,
grid: true,
width: 750,
height: 750,
marginLeft: 50, // space to the left of the chart
marginBottom: 50, // space below the chart
color: {
legend: true,
},
// facet: {
// data: baseData,
// x: "continent"
// },
x: {
// label: "GDP per capita (USD) →",
tickFormat: "~s",
type: "log",
ticks: 3
},
y: {
// label: "↑ Population (people)",
type: "log",
tickFormat: "~s",
// textColor: "white",
ticks: 5
},
marks: [
//dots
Plot.dot(baseData, {x: "gdp_capita_2019", y: "urban_2019", text: "iso3", stroke: "continent"}),
// Plot.dot(data_gdpc, {x: "gdp_capita_2050", y: "urban_2050_a", text: "iso3", stroke: "continent"}),
//text
Plot.text(baseData, {x: "gdp_capita_2019", y: "urban_2019", text: "city", font: "IBM Plex Sans",
fill: "continent",
stroke: "white",
opacity: 1,
fontSize: 12}),
// Plot.text(baseData, {x: "gdp_capita_2050", y: "urban_2050_a", text: "city",
// fill: "continent",
// // stroke: "white",
// opacity: 0.8,
// fontSize: 11}),
//links
Plot.link(baseData, {
x1: "gdp_capita_2019",
y1: "urban_2019",
x2: "gdp_capita_2050",
y2: "urban_2050_a",
stroke: "continent",
markerEnd: "arrow",
strokeWidth: 1.5,
opacity: 0.5
}),
]
})
Insert cell
baseData[0]
Insert cell
test = Plot.plot({
inset: 8,
grid: true,
width: width*1.25,
height: 750,
marginLeft: 50, // space to the left of the chart
marginBottom: 50, // space below the chart
color: {
legend: true,
},
facet: {
data: baseData,
x: "continent"
},
x: {
// label: "GDP per capita (USD) →",
tickFormat: "~s",
type: "log",
ticks: 3
},
y: {
// label: "↑ Population (people)",
type: "log",
tickFormat: "~s",
// textColor: "white",
ticks: 5
},
marks: [
//dots
// Plot.dot(data_gdpc, {x: "gdp_capita_2019", y: "urban_2019", text: "iso3", stroke: "continent"}),
// Plot.dot(data_gdpc, {x: "gdp_capita_2050", y: "urban_2050_a", text: "iso3", stroke: "continent"}),
//text
Plot.text(baseData, {x: "gdp_capita_2019", y: "urban_2019", text: "city",
fill: "continent",
// stroke: "white",
opacity: 0.8,
fontSize: 11}),
Plot.text(baseData, {x: "gdp_capita_2050", y: "urban_2050_a", text: "city",
fill: "continent",
// stroke: "white",
opacity: 0.8,
fontSize: 11}),
//links
Plot.link(baseData, {
x1: "gdp_capita_2019",
y1: "urban_2019",
x2: "gdp_capita_2050",
y2: "urban_2050_a",
stroke: "continent",
markerEnd: "arrow",
opacity: 0.3
}),
]
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
pColor = ({'urban_2019': "#A2D6F9", 'urban_2050_c': "#2D76F0"})
Insert cell
gColor = ({'gdp_urban_2019': "#f6aa1c", 'gdp_urban_2050_c': "#bc3908"})

Insert cell
Insert cell
Insert cell
popnScale = d3.scaleLinear().domain(popnDomain).range(radiusRange);
Insert cell
gdpScale = d3.scaleLinear().domain(gdpDomain).range(radiusRange);
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
selectedPopns[0]
Insert cell
computedPopns = {
let popns = []
for (let i in selectedPopns){
let row = selectedPopns[i];
let gdpGap = row['gdp_urban_2050_c'] - row['gdp_urban_2019'];
let popnGap = row['urban_2050_c'] - row['urban_2019'];
row['gdpGap'] = gdpGap;
row['popnGap'] = popnGap;
popns.push(row);
}
return popns;
}
Insert cell
Insert cell
Insert cell
cleanData = FileAttachment("data.csv").csv({typed: true})
Insert cell
baseData = FileAttachment("urban-data-growth-gdpc-full@2.csv").csv()
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
import {slider} from "@jashkenas/inputs"
Insert cell
import {Swatches} from "@d3/color-legend"
Insert cell
import {mapProjection, activeColorScheme, worldMap} from "b3a0a78984d6df2e"
Insert cell
import {rangeSlider} from '@mootari/range-slider'
Insert cell
viewof range = Inputs.range([0, 100], {label: "Amount", step: 1})
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