Public
Edited
Mar 7
3 forks
2 stars
Insert cell
Insert cell
viewof options = checkbox({
options: ["Separate", "Order", "Align"],
value : ["Separate", "Order", "Align"]
})
Insert cell
chart = {
const separate = options.includes("Separate"),
order = options.includes("Order"),
align = options.includes("Align");

const y = vl
.y()
.fieldN("Country Name")
.sort(order ? vl.fieldQ(selectedSeries).order("descending") : "y");

const base = vl
.mark({ type: separate ? "bar" : "tick", tooltip: { data: true } })
.data(filteredData)
.encode(
align
? vl.x().fieldQ(selectedSeries).axis({ orient: "top" })
: vl.x().fieldQ("latitude").axis(null),
align ? null : vl.x2().fieldQ("latitudePlusGdp"),
separate ? y : null
);

const withText = vl.layer(
base,
base
.markText({ align: "left", dx: 2, size: 14 })
.encode(vl.text().fieldQ(selectedSeries).format("$0.2s"))
);

return (separate ? withText : base)
.config({
axis: {
labelFontSize: 12
}
})
.width(300)
.render();
}
Insert cell
options
Insert cell
Insert cell
data = FileAttachment("GDP_2019_WDI@1.csv")
.text()
.then(res => d3.csvParse(res, d3.autoType))
.then(res => res.filter(d => d["Series Name"]!==null && +d[year]))
Insert cell
md`For simplicity we show only the top 20 countries`
Insert cell
filteredData = data
.filter(d => d["Series Name"] === selectedSeries).sort((a,b) => b[year]-a[year])
.slice(0, 20)
.map(d => {
d[selectedSeries]= +d[year];
// Values for unaligned chart
d.latitude = +mapLatitudes.get(d["Country Code"]).latitude;
d.latitudePlusGdp = +d.latitude + gdpToLatitude(d[selectedSeries]) + gdpToLatitude.range()[0];
return d;
})
Insert cell
viewof selectedSeries = select(series)
Insert cell
year = "2019 [YR2019]"
Insert cell
series = Array.from(d3.group(data, d=> d["Series Name"]).keys())
Insert cell
md` For computing the latitude of each country`
Insert cell
gdpToLatitude = {
const latsExtent = d3.extent(mapLatitudes.values(), d=> +d.latitude);
return d3.scaleLinear()
.domain([0, d3.max(data, d=> d[year])])
.range([0, latsExtent[1]-latsExtent[0]])
}
Insert cell
mapLatitudes = new Map(
await fetch("https://api.worldbank.org/v2/country?format=json&per_page=350")
.then((res) => res.json())
.then((res) => res[1].map((d) => [d.id, d]))
)
Insert cell
Insert cell
d3 = require("d3-dsv", "d3-array", "d3-scale")
Insert cell
import {vl} from "@vega/vega-lite-api"
Insert cell
import {select, checkbox} from "@jashkenas/inputs"
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