Published
Edited
Sep 14, 2022
Insert cell
Insert cell
chart = BarChart(data)
Insert cell
data = [
{
name: 'Tokyo',
height: 37.43
},
{
name: 'Delhi',
height: 29.39
},
{
name: 'Shanghai',
height: 26.31
},
{
name: 'Sao Paulo',
height: 21.85
},
{
name: 'Mexico City',
height: 21.67
},
{
name: 'Cairo',
height: 20.48
},
{
name: 'Dhaka',
height: 20.28
},
{
name: 'Mumbai',
height: 20.18
},
{
name: 'Beijing',
height: 20.03
},
{
name: 'Osaka',
height: 19.22
},
]
Insert cell
function BarChart(data, {
margin = { top: 10, bottom: 40, left: 100, right: 0 },
width = 640,
height = 400,
xDomain = d3.groupSort(data, ([d]) => -d.height, d => d.name),
} = {}) {

const x = d3.scaleBand()
.domain(data.map(d => d.name))
.range([margin.left, width - margin.right])
.padding(0.2);
const y = d3.scaleLinear()
.domain([
0,
d3.max(data, d => d.height)
])
.range([height, 0])

const yAxis = d3.axisLeft(y);
const xAxis = d3.axisBottom(x);

xAxis.tickPadding([0.3])

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height + 50)
//min-x, min-y, width and height
.attr("viewBox", [0, 0, width, height + margin.top + margin.bottom])
.attr("style", "max-width: 100%; height: auto; height: intrinsic;");

svg.append("g")
.attr("transform", `translate(${margin.left}, 0)`)
.call(yAxis)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width - margin.left - margin.right)
.attr("stroke-opacity", 0.1))
.attr("fill", "seagreen")
.call(g => g.append("text")
.attr("x", -(height / 2))
.attr("text-anchor", "middle")
.attr("y", -30 )
.text("↑ millions of inhabitants")
.attr("transform", "rotate(-90)"));
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(xAxis);

const bar = svg.append("g")
.attr("fill", "seagreen")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.name))
.attr("y", d => y(d.height))
.attr("height", d => height - y(d.height))
.attr("width", x.bandwidth());



return svg.node();
}
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