Published
Edited
Aug 12, 2020
2 forks
Insert cell
Insert cell
chart = {
const root = d3.create("div")
.attr("class", "root");
const svg = root.append("svg")
.attr("viewBox", [0, 0, width, height]);
const tooltip = root
.append("div")
.attr("class", "cooltip");

svg.append("g").call(xAxis);

svg.append("g").call(yAxis);
svg
.append("g")
.selectAll("g")
.data(data)
.join("g")
.attr("transform", d => `translate(${x0(d[groupKey])},0)`)
.selectAll("rect")
.data(d => keys.map(key => ({ key, value: d[key] })))
.join("rect")
.attr("x", d => x1(d.key))
.attr("y", d => y(d.value))
.attr("width", x1.bandwidth())
.attr("height", d => y(0) - y(d.value))
.attr("fill", d => color(d.key))
.on('mouseover', function(d) {
this.classList.add('hovered');
d3.select(this)
.attr("stroke", "black")
.raise();
tooltip.style('display', '');
let node = tooltip.node();
node.innerHTML = "";
node.appendChild(getTooltipContents(d));
})
.on('mousemove', function() {
const rootBounds = root.node().getBoundingClientRect();
const mouseX = d3.event.pageX - rootBounds.left;
const mouseY = d3.event.pageY - rootBounds.top;
tooltip
.style('top', Math.min((mouseY - 10), root.node().offsetHeight - 95) + 'px')
.style('left', (mouseX + 135 <= root.node().offsetWidth ? (mouseX + 10) : (mouseX - 145)) + 'px')
.style('display', 'block')
})
.on('mouseout', function() {
this.classList.remove('hovered');
d3.select(this)
.attr("stroke", null)
.lower();
tooltip.style('display', 'none');
});
svg.append("g")
.call(legend);
window.addEventListener("resize", () => resized(width, root, svg));
setTimeout(() => resized(width, root, svg), 12);
return root.node();
}
Insert cell
legend = svg => {
const g = svg
.attr("transform", `translate(${width},0)`)
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(color.domain().slice().reverse())
.join("g")
.attr("transform", (d, i) => `translate(0,${i * 20})`);

g.append("rect")
.attr("x", -19)
.attr("width", 15)
.attr("height", 15)
.attr("fill", color);

g.append("text")
.attr("x", -24)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
function resized(width, root, svg) {
let measuredWidth = root.node().getBoundingClientRect().width;
if (measuredWidth == 0) {
setTimeout(() => resized(width, root, svg), 12);
return;
}
let scale = width / measuredWidth;
svg.selectAll("line").attr("stroke-width", scale + "px");
svg.selectAll("text").attr("transform", "scale(" + scale + " " + scale + ")");
}
Insert cell
getTooltipContents = d => {
return html` <div class = "container">
<div class = "num"> ${d.key}: ${d.value}</div>
`;
}
Insert cell
html`
<style>
.cooltip {
background: white;
border: 1px solid lightgrey;
padding: 10px;
position: absolute;
font-family: Helvetica, Arial, sans-serif;
}
.num {
font-size: 14px;
}
</style>
`
Insert cell
x0 = d3.scaleBand()
.domain(data.map(d => d[groupKey]))
.rangeRound([margin.left, width - margin.right])
.paddingInner(0.1)
Insert cell
x1 = d3.scaleBand()
.domain(keys)
.rangeRound([0, x0.bandwidth()])
.padding(0.05)
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d3.max(keys, key => d[key]))]).nice()
.rangeRound([height - margin.bottom, margin.top])
Insert cell
color = d3.scaleOrdinal()
.range(["#F5B48F", " #D0B3BC"])
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.style("font-size", "12px")
.call(
d3
.axisBottom(x0)
.tickSizeOuter(0)
.tickSize(0)
)
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.style("font-size", "12px")
.call(d3.axisLeft(y)
.ticks(height / 80, data.format)
.tickSize(0))
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick:not(:first-of-type) line")
.attr("stroke-dasharray", "2,2")
.attr("stroke-opacity", d => d === 1 ? null : 0.25)
.attr("x2", width - margin.left - margin.right))
Insert cell
data = Object.assign(
d3.csv(
"https://raw.githubusercontent.com/prayaggordy/D3-covid-map/master/data/race_data.csv",
d3.autoType
),
{ y: "Population" }
)
Insert cell
groupKey = data.columns[0]
Insert cell
keys = data.columns.slice(1)
Insert cell
margin = ({top: 20, right: 10, bottom: 20, left: 55})
Insert cell
height = 250
Insert cell
width = 450
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