Published
Edited
Feb 27, 2021
Insert cell
md`# Population Density`
Insert cell
Insert cell
Insert cell
embed = require('vega-embed')
Insert cell
d3 = require('d3')
Insert cell
Insert cell
scheme = ({
$schema: "https://vega.github.io/schema/vega-lite/v4.json",
data: {
values: undata
},
transform: [
{ filter: "datum.Densitysqkm >= 1000" },
{ calculate: "datum.Population/1000000", as: "popInmillion" }
],
mark: "circle",
selection: {
pandz: {
type: "interval",
bind: "scales",
encodings: ["x", "y"]
}
},
encoding: {
x: {
field: "Country",
title: "Country",
sort: { field: "Densitysqkm", order: "descending" },
axis: { grid: true, title: "Country" }
},
y: {
bin: { maxbins: 100 },
field: "Densitysqkm",
sort: "ascending",
axis: { title: "Population in million" }
},
size: {
field: "Densitysqkm",
type: "quantitative"
},
color: {
field: "Densitysqkm",
type: "quantitative",
scale: { range: ["red", "green"] }
},
tooltip: [{ field: "Densitysqkm" }, { field: "Country" }]
},
config: {
axis: { domainWidth: 2 }
}
})
Insert cell
embed(scheme)
Insert cell
filtdata = undata.filter(d => d.Densitysqkm > 300)
Insert cell
vl
.layer(
vl
.markBar()
.encode(
vl
.color()
.fieldN("Continent")
.legend({ orient: "top" }),
vl
.y()
.fieldQ('PopInmillion')
.axis({ grid: true })
.sort(vl.field("Population").order('descending'))
)
.select(
vl
.selectInterval()
.bind("scales")
.encodings("y")
),
vl
.layer(
vl.markCircle().encode(vl.size().fieldQ('DensityKsqkm')),
vl.markLine().select(
vl
.selectInterval()
.bind("scales")
.encodings("y")
)
)
.encode(
vl.y().fieldQ('DensityKsqkm'),
vl.tooltip(["Continent", "Densitysqkm", "PopInmillion"])
)
)
.resolve({ scale: { y: "independent" } })
.data(filtdata)
.transform(
vl.calculate("datum.Densitysqkm/1000").as("DensityKsqkm"),
vl.calculate("datum.Population/1000000").as("PopInmillion")
)
.title("Population Density from UN Data")
.encode(
vl
.x()
.fieldN('Country')
.axis({ grid: true }),

vl.tooltip([
"Continent",
"Densitysqkm",
"DensityBAsqkm",
"Population",
"PopInmillion"
])
)
.width(width * .8)
.render()
Insert cell
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