{
let w = 800;
let h = 500;
let svg = d3
.create("svg")
.attr("width", "100%")
.attr("viewBox", [0, 0, w, h])
.style("border", "solid 1px black");
let bins = d3.bin().value((o) => o.salary)(faculty_salaries);
let ymax = d3.max(bins, (a) => a.length);
let [xmin, xmax] = d3.extent(faculty_salaries, (o) => o.salary);
let xwidth = xmax - xmin;
xmin = xmin - 0.1 * xwidth;
xmax = xmax + 0.1 * xwidth;
let data = [];
bins.forEach(function (a) {
let up_to_here = 0;
let groups = d3.group(a, (o) => o.title);
titles.forEach(function (title) {
let this_data = groups.get(title);
if (this_data) {
// Push the current data on our data stack
data.push({
x0: a.x0,
x1: a.x1,
title: this_data[0].title,
cnt: this_data.length,
up_to_here
});
// And keep track of how much data we've accumulated in this bin
up_to_here = up_to_here + this_data.length;
}
});
});
// End tricky new stuff.
// You can see what the data looks like by uncommenting this line:
// return data;
let pad = 50;
let x_scale = d3
.scaleLinear()
.domain([xmin, xmax])
.range([pad, w - pad]);
let y_scale = d3
.scaleLinear()
.domain([0, ymax])
.range([h - pad, pad]);
let path = d3
.line()
.x((d) => x_scale(d[0]))
.y((d) => y_scale(d[1]));
// The width of each bin and a normalizer
// to get the areas of the bins to be 1.
let dx = bins[1].x1 - bins[1].x0;
// Draw the y-axis
svg
.append("g")
.attr("transform", `translate(${pad})`)
.call(d3.axisLeft(y_scale).tickSizeOuter(0))
.call((g) =>
g
.selectAll(".tick line")
.clone()
.attr("x2", width)
.attr("stroke-opacity", 0.2)
);
// Set up the rectangles
let rect_group = svg
.append("g")
.attr("stroke", "white")
.attr("stroke-width", 2);
rect_group
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (b) => x_scale(b.x0))
.attr("width", (b) => x_scale(b.x1) - x_scale(b.x0))
.attr("y", (b) => y_scale(b.up_to_here + b.cnt)) // Note the rects are initial right on the x-axis
.attr("height", (b) => y_scale(0) - y_scale(b.cnt))
.attr("fill", (o) => instructor_color(o.title))
// Highlight the nodes on pointer enter.
.on("pointerenter", function () {
d3.select(this).attr("stroke", "black").raise();
})
.on("pointerleave", function () {
d3.select(this).attr("stroke", "white");
})
// Attach the tooltip as a native SVG title
.append("title")
.text((o) => `${o.cnt} ${o.title}`);
// Draw the axes
svg
.append("g")
.attr("transform", `translate(0, ${y_scale(0)})`)
.call(d3.axisBottom(x_scale).tickSizeOuter(0));
return svg.node();
}