Published
Edited
May 1, 2019
Insert cell
Insert cell
Insert cell
Insert cell
viewof selected_institution = select({
title: "Selected institution",
options: institutions,
value: 0
})
Insert cell
viewof selected_inoutflow = html`<select>
<option>Inflow
<option>Outflow
</select>`
Insert cell
viewof selected_year = slider({
message: "A sample slider that does nothing!",
min: 1980,
max: 2015,
start: 1980,
step: 5,
int: true
})
Insert cell
map = {

const context = this ? this.getContext("2d") : DOM.context2d(size, size);
const render = function() {
const path = d3.geoPath(projection, context);
const rotate = projection.rotate();
const backpath = d3.geoPath(backprojection, context);
const frontColor = d3.hcl('#a9c681');
const backColor = d3.hcl(frontColor);
backColor.l += 15;
backColor.c -= 30;
context.clearRect(0, 0, width, width);

context.beginPath(), path({type:"Sphere"}),
context.fillStyle = '#fcfcfc', context.fill();

context.beginPath(), backpath(countries),
context.fillStyle = backColor, context.fill();

context.beginPath(), backpath(d3.geoGraticule()()),
context.lineWidth = .1, context.strokeStyle = '#aaa', context.stroke();

context.beginPath(), path(d3.geoGraticule()()),
context.lineWidth = .1, context.strokeStyle = '#111', context.stroke();

context.beginPath(), path(countries),
context.globalAlpha = 0.9,
context.lineWidth = 1, context.strokeStyle = frontColor.darker(1), context.stroke(),
context.fillStyle = frontColor, context.fill(),
context.globalAlpha = 1;

context.beginPath(), path({type: "Sphere"}),
context.lineWidth = .1, context.strokeStyle = '#111', context.stroke();

context.beginPath(), path(selectedData);
context.lineWidth = 1, context.strokeStyle = selectedColor, context.stroke()
context.beginPath(), path({type: 'Point', coordinates: selectedPlace});
context.fillStyle = "red", context.fill()
context.beginPath(), path({type: 'LineString', coordinates:[projection]})
context.lineWidth = 1, context.strokeStyle = selectedColor, context.stroke()
// Flying arc

}


// no need to specify render() here, it's taken care of by the loop below.
context.canvas.inertia = d3.geoInertiaDrag(d3.select(context.canvas), null, projection);

const timer = d3.timer(function() {
var rotate = projection.rotate();
rotate[0] += velocity * 20;
projection.rotate(rotate);
backprojection.rotate(rotate);
render();
});
invalidation.then(() => (timer.stop(), timer = null, d3.select(context.canvas).on(".drag", null)));

return context.canvas;

}
Insert cell
Insert cell
Insert cell
viewof distance = {
const inputToDistance = x => x ** 2;
const distanceToInput = x => Math.sqrt(x);

const form = DOM.element("form");
form.value = 3
const input = html`<input id='distance' type='range' step='any' min='${distanceToInput(1.1)}' max='${distanceToInput(20)}'></input>`;
input.value = distanceToInput(form.value);
input.addEventListener("input", () => form.value = inputToDistance(input.valueAsNumber));
form.appendChild(input);
return form;
}
Insert cell
Insert cell
projection = d3.geoSatellite()
.distance(distance)
.clipAngle(Math.acos(1 / distance) * 180 / Math.PI - 1e-6)
.precision(0.1)
.fitExtent([[5, 5], [size - 5, size - 5]], {type: "Sphere"})
Insert cell
projection.invert([0,0])
Insert cell
loftedProjection = d3.geoSatellite()
.distance(distance)
.clipAngle(Math.acos(1 / distance) * 180 / Math.PI - 1e-6)
.precision(0.1)
.fitExtent([[5, 5], [(size - 5)*1.3, (size - 5)*1.3]], {type: "Sphere"})
Insert cell
function locationAlongArc(start, end, theta) {
return d3.geoInterpolate(start, end)(theta);
}
Insert cell
function flyingArc(link) {
var source = [0,0],
target = [50,50],
middle = locationAlongArc(source, target, 0.5);
return [
projection(source),
loftedProjection(middle),
projection(target)
];
}
Insert cell
Insert cell
function lineLength(points) {
var d = 0;
for (var i = 0; i < points.length - 1; i++) {
var x0 = points[0][0],
y0 = points[0][1],
x1 = points[1][0],
y1 = points[1][1],
dx = x1 - x0,
dy = y1 - y0;
d += Math.sqrt(dx * dx + dy * dy);
}
return d;
}
Insert cell
Insert cell
Insert cell
Insert cell
Url="https://gist.githubusercontent.com/zhengyunhan/6bae5a5d7872ea314ca155281865fcc3/raw/820ee002c06751c4689e6f7a64318446cdd54fae/select_inflow.csv"
Insert cell
Url2="https://gist.githubusercontent.com/zhengyunhan/ec0cba9408754fc0b38ae90b4dd65a10/raw/3ff848f89d4ebd2ded2c698f1697e18c9a4c3afa/select_outflow.csv"
Insert cell
Urlin="https://gist.githubusercontent.com/zhengyunhan/dc9bf727352a5fd307381879bd3757d0/raw/6475356b1a569c48bf360b4fe970464092fbbf4f/inflow_5year.csv"
Insert cell
Urlout="https://gist.githubusercontent.com/zhengyunhan/2389b3d6abb6a4afa37daaa8368bba7d/raw/34e9ce9ab5bfa1ae8b417a43d47b4c816a98655b/outflow_5year.csv"
Insert cell
Inflow=d3.csv(Urlin)
Insert cell
Outflow=d3.csv(Urlout)
Insert cell
arc_inflow={
let features=[]
for (let i=0; i<selected_inflow.length; i++){
features.push({type: "Feature", geometry: {type:"LineString",coordinates:[[parseFloat(selected_inflow[i].lng), parseFloat(selected_inflow[i].lat)], [parseFloat(selected_inflow[i].des_lng), parseFloat(selected_inflow[i].des_lat)]]}},)
}
return {
type: "FeatureCollection",
features: features
}
}
Insert cell
arc_outflow={
let features=[]
for (let i=0; i<selected_outflow.length; i++){
features.push({type: "Feature", geometry: {type:"LineString",coordinates:[[parseFloat(selected_outflow[i].lng), parseFloat(selected_outflow[i].lat)], [parseFloat(selected_outflow[i].des_lng), parseFloat(selected_outflow[i].des_lat)]]}},)
}
return {
type: "FeatureCollection",
features: features
}
}
Insert cell
selectedData = {
switch (selected_inoutflow) {
case "Inflow": return arc_inflow
case "Outflow": return arc_outflow
}
}
Insert cell
selectedColor = {
switch (selected_inoutflow) {
case "Inflow": return "rgba(0,100,0,.4)"
case "Outflow": return "rgba(100,0,0,.4)"
}
}
Insert cell
selectedPlace = {
switch (selected_inoutflow) {
case "Inflow": return [selected_inflow[0].des_lng,selected_inflow[0].des_lat]
case "Outflow": return [selected_outflow[0].lng,selected_outflow[0].lat]
}
}
Insert cell
selected_inflow=z.filter(r => r[selected_institution] == 1 & r.year == selected_year, Inflow)
Insert cell
selected_outflow=z.filter(r => r[selected_institution] == 1 & r.year == selected_year, Outflow)
Insert cell
institutions=Object.keys(Inflow[0]).slice(14)
Insert cell
z.unique(selected_inflow)
Insert cell
size = width * 0.8
Insert cell
Insert cell
land = topojson.feature(world, world.objects.land)
Insert cell
countries = topojson.feature(world, world.objects.countries)
Insert cell
Insert cell
Insert cell
d3 = require("d3-format", "d3-fetch@0.1", "d3-geo@1", "d3-geo-projection", "d3-geo-polygon", "d3-selection", "d3-timer", "d3-inertia", "d3-color")
Insert cell
z = require('https://bundle.run/zebras@0.0.11')
Insert cell
versor = require("versor@0.0.3")
Insert cell
// import {select} from "@jashkenas/inputs"
Insert cell
function select(config = {}) {
let {
value: formValue,
title,
description,
submit,
multiple,
size,
options
} = config;
if (Array.isArray(config)) options = config;
options = options.map(
o => (typeof o === "object" ? o : { value: o, label: o })
);
const form = input({
type: "select",
title,
description,
submit,
getValue: input => {
const selected = Array.prototype.filter
.call(input.options, i => i.selected)
.map(i => i.value);
return multiple ? selected : selected[0];
},
form: html`
<form>
<select name="input" ${
multiple ? `multiple size="${size || options.length}"` : ""
}>
${options.map(({ value, label }) => Object.assign(html`<option>`, {
value,
selected: Array.isArray(formValue)
? formValue.includes(value)
: formValue === value,
textContent: label
}))}
</select>
</form>
`
});
form.output.remove();
return form;
}
Insert cell
function input(config) {
let {
form,
type = "text",
attributes = {},
action,
getValue,
title,
description,
format,
display,
submit,
options
} = config;
const wrapper = html`<div></div>`;
if (!form)
form = html`<form>
<input name=input type=${type} />
</form>`;
Object.keys(attributes).forEach(key => {
const val = attributes[key];
if (val != null) form.input.setAttribute(key, val);
});
if (submit)
form.append(
html`<input name=submit type=submit style="margin: 0 0.75em" value="${
typeof submit == "string" ? submit : "Submit"
}" />`
);
form.append(
html`<output name=output style="font: 14px Menlo, Consolas, monospace; margin-left: 0.5em;"></output>`
);
if (title)
form.prepend(
html`<div style="font: 700 0.9rem sans-serif;">${title}</div>`
);
if (description)
form.append(
html`<div style="font-size: 0.85rem; font-style: italic;">${description}</div>`
);
if (format) format = typeof format === "function" ? format : d3format.format(format);
if (action) {
action(form);
} else {
const verb = submit
? "onsubmit"
: type == "button"
? "onclick"
: type == "checkbox" || type == "radio"
? "onchange"
: "oninput";
form[verb] = e => {
e && e.preventDefault();
const value = getValue ? getValue(form.input) : form.input.value;
if (form.output) {
const out = display ? display(value) : format ? format(value) : value;
if (out instanceof window.Element) {
while (form.output.hasChildNodes()) {
form.output.removeChild(form.output.lastChild);
}
form.output.append(out);
} else {
form.output.value = out;
}
}
form.value = value;
if (verb !== "oninput")
form.dispatchEvent(new CustomEvent("input", { bubbles: true }));
};
if (verb !== "oninput")
wrapper.oninput = e => e && e.stopPropagation() && e.preventDefault();
if (verb !== "onsubmit") form.onsubmit = e => e && e.preventDefault();
form[verb]();
}
while (form.childNodes.length) {
wrapper.appendChild(form.childNodes[0]);
}
form.append(wrapper);
return form;
}
Insert cell
d3format = require("d3-format@1")
Insert cell
function slider({
message = 'Set your value',
min = 0,
max = 1,
start = 0.5,
step = 0.1,
precision = 3,
int = false,
}){
min = min/step;
max = max/step;
start = start/step;
const div = html`
<a>${message}</a>
<input type=range min=${min} max=${max} value = ${start}>
<span>${start*step}</span>
`;
const range = div.querySelector("[type=range]");
const value_disp = div.querySelector('span');
div.value = value_disp.innerHTML = start*step;

range.addEventListener("input", () => {
const newValue = range.valueAsNumber*step;
div.value = newValue;
value_disp.innerHTML = int ? Math.round(newValue) : newValue.toPrecision(precision);
});
return div;
}
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