Published
Edited
Apr 4, 2020
Importers
2 stars
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(Array.from(counts))
.join("rect")
.attr("x", d => x(0))
.attr("width", d => x(d[1]) - x(0))
.attr("y", d => y(d[0]))
.attr("height", y.bandwidth());

svg.append("g")
.call(xAxis);
svg.append("g")
.call(yAxis);
return svg.node();
}
Insert cell
data = 'thequickbrownfoxjumpedoverthelazydog'.split('')
Insert cell
maxItems = 15
Insert cell
otherName = "*Other"
Insert cell
counts = {
const counts = d3.rollup(data, d => d.length, d => d);
if (counts.size > maxItems) {
const sorted = Array.from(counts).sort((a,b) => d3.descending(a[1], b[1]));
const keysToRemove = new Set(sorted.slice(maxItems).map(d => d[0]));
const otherCount = d3.sum(sorted.filter(d => keysToRemove.has(d[0])).map(d => d[1]));
keysToRemove.forEach(k => counts.delete(k));
counts.set(otherName, otherCount);
}
return counts;
}
Insert cell
x = d3.scaleLinear()
.domain([0,d3.max(counts.values())]).nice()
.range([margin.left, width - margin.right])
Insert cell
x.domain()
Insert cell
sorter = (a,b) => {
if (a === otherName) return -1;
if (b === otherName) return 1;
return d3.ascending(counts.get(a),counts.get(b));
}
Insert cell
y = d3.scaleBand()
.domain([...counts.keys()].sort(sorter))
.range([height - margin.bottom, margin.top])
.padding(0.1)
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80 ).tickSizeOuter(0))
.call(g => g.append("text")
.attr("x", width - margin.right)
.attr("y", -4)
.attr("fill", "currentColor")
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.text(data.x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickSizeOuter(0));
Insert cell
height = 500
Insert cell
margin = ({top: 20, right: 20, bottom: 30, left: 40})
Insert cell
d3 = require("d3@5", "d3-array")
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