chart = {
const width = 640;
const height = 400;
const marginTop = 20;
const marginRight = 0;
const marginBottom = 30;
const marginLeft = 40;
const default_color = "steelblue";
const highlight_color = "orange";
const x = d3.scaleBand()
.domain(data.map(d => d.letter))
.range([marginLeft, width - marginRight])
.padding(0.1);
const xAxis = d3.axisBottom(x).tickSizeOuter(0);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.frequency)]).nice()
.range([height - marginBottom, marginTop]);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("style", `max-width: ${width}px; height: auto; font: 10px sans-serif; overflow: visible;`);
const tooltip = d3.select("body").append("div")
.style("position", "absolute")
.style("visibility", "hidden")
.style("background", "white")
.style("border", "1px solid #000")
.style("padding", "3px")
.style("border-radius", "3px")
.style("font", "12px sans-serif")
const bar = svg.append("g")
.attr("fill", default_color)
.selectAll("rect")
.data(data)
.join("rect")
.style("mix-blend-mode", "multiply")
.attr("x", d => x(d.letter))
.attr("y", d => y(d.frequency))
.attr("height", d => y(0) - y(d.frequency))
.attr("width", x.bandwidth())
bar
.on('mouseover', (event, d) => {
tooltip
.style('visibility', 'visible')
.html(`<strong>Letter: ${d.letter}</strong><br/>Frequency: ${(d.frequency * 100).toFixed(1)}%`);
const bar = d3.select(event.currentTarget);
if (!bar.classed('clicked')) {
bar.attr('fill', highlight_color);
}
})
.on('mousemove', (event) => {
tooltip
.style('left', (event.pageX + 10) + 'px')
.style('top', (event.pageY + 10) + 'px');
})
.on('mouseleave', (event) => {
tooltip.style('visibility', 'hidden');
const bar = d3.select(event.currentTarget);
if (!bar.classed('clicked')) {
bar.attr('fill', default_color);
}
})
.on('click', (event) => {
const bar = d3.select(event.currentTarget);
const clicked = bar.classed('clicked');
bar.classed('clicked', !clicked);
bar.attr('fill', clicked ? default_color : highlight_color);
});
const gx = svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(xAxis);
const gy = svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y).tickFormat((y) => (y * 100).toFixed()))
.call(g => g.select(".domain").remove());
function update(order) {
x.domain(data.sort(order).map(d => d.letter));
bar.data(data, d => d.letter)
.order()
.transition()
.duration(750)
.delay(50)
.attr("x", d => x(d.letter))
.attr("y", d => y(d.frequency));
gx.transition()
.duration(750)
.delay(50)
.call(xAxis)
.selectAll(".tick");
};
return Object.assign(svg.node(), {update});
}