Public
Edited
May 7, 2024
Insert cell
Insert cell
data
Insert cell
selection
Insert cell
viewof selection = {
let selection = data; // the initial selection

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.property("value", selection);

const rect = svg.append("g")
.attr("fill", "#d3d3d3")
.selectAll("rect")
.data(bins)
.join("rect")
.attr("x", d => x(d.x0) + 1)
.attr("width", d => Math.max(0, x(d.x1) - x(d.x0) - 1) - 3)
.attr("y", d => y(d.length))
.attr("height", d => y(0) - y(d.length))
.on("click", (event, d) => {
if (selection === d) { // toggle
selection = data;
} else {
selection = d;
}
rect.attr("fill", d => selection === d ? "#004F5B" : null);
svg.property("value", selection).dispatch("input");
});

svg.append("g")
.call(xAxis)
svg.append("g")
.call(yAxis);
return svg.node();
}
Insert cell
data = [
{count: 7, id: "a" },
{count: 8, id: "b" },
{count: 16, id: "c" },
{count: 7, id: "d" },
{count: 13, id: "e" },
{count: 14, id: "f" },
{count: 6, id: "g" },
{count: 6, id: "h" },
{count: 1, id: "i" },
{count: 10, id: "j" },
{count: 12, id: "k" },
{count: 9, id: "l" },
{count: 14, id: "m" },
{count: 4, id: "n" },
{count: 3, id: "o" },
{count: 10, id: "p" },
{count: 16, id: "q" },
{count: 17, id: "r" },
{count: 16, id: "s" },
{count: 18, id: "t" },
{count: 7, id: "u" },
{count: 13, id: "v" },
{count: 10, id: "w" },
{count: 20, id: "x" }
]
Insert cell
th = 3
Insert cell
bins = d3.bin().thresholds(3).value(x => x.count)(data)
Insert cell
x = d3.scaleLinear()
.domain([bins[0].x0, bins[bins.length - 1].x1])
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(bins, d => d.length)]).nice()
.range([height - margin.bottom, margin.top])
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))
.attr("font-size", 15)
.attr('color', "#004F5B")
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(height / 40))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 4)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
.attr("font-size", 15)
.attr('color', "#004F5B")
Insert cell
height = 900
Insert cell
margin = ({top: 20, right: 20, bottom: 30, left: 40})
Insert cell
d3 = require("d3@^6.2.0")
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