Published
Edited
Dec 6, 2020
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));
svg.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", x(0))
.attr("y", d => y(d.language))
.attr("width", d => x(d.percentage) - x(0))
.attr("height", y.bandwidth());
svg.append("g")
.attr("fill", "white")
.attr("text-anchor", "end")
.style("font", "12px sans-serif")
.selectAll("text")
.data(data)
.join("text")
//.attr("x", d => x(d.percentage) - 4)
.attr("x", d => x(d.percentage))
.attr("y", d => y(d.language) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("dx", -4)
//.text(d => format(d.percentage))
.text(d => f(d.percentage) + "%")
.call(text => text.filter(d => x(d.percentage) - x(0) < 100) // short bars
.attr("dx", +4)
.attr("fill", "black")
.attr("text-anchor", "start"));
svg.append("g")
.call(xAxis);
svg.append("g")
.style("font", "13.5px times")
.style("font-weight", "bold")
.call(yAxis);
return svg.node();
}
Insert cell
data = d3.csvParse(await FileAttachment("Austria Hungary languages - Sheet2 (1).csv").text(), ({language, percentage}) => ({language: language, percentage: +percentage})).sort((a, b) => b.percentage - a.percentage)
Insert cell
f = d3.format(".2f")
Insert cell
format = x.tickFormat(20)
Insert cell
x = d3.scaleLinear()
.domain([0, d3.max(data, d => d.percentage)])
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(data.map(d => d.language))
.range([margin.top, height - margin.bottom])
.padding(0.1)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(width / 80))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickSizeOuter(0))
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
height = (data.length * 25 + margin.top + margin.bottom)*2
Insert cell
margin = ({top: 30, right: 0, bottom: 10, left: 100})
Insert cell
d3 = require("d3@5")
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