Public
Edited
Mar 30, 2024
3 stars
Insert cell
Insert cell
chart = {
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;

const svg = d3
.create("svg")
.style("cursor", "default")
.attr("viewBox", [0, 0, chartWidth, chartHeight])
.attr("tabindex", 0) // add tabindex attribute to enable focus
.style("background", "white");

const g = svg
.selectAll(".waffle")
.data(wafflesData)
.join("g")
.attr("class", "waffle")
.attr("aria-label", (d, i) => `${data[i].category}-${data[i].value}%`);

const numPerRow = Math.floor(
chartWidth / (sizeOfWaffle + paddingBetweenWaffles.x)
);

g.attr("transform", (d, i) => {
const r = Math.floor(i / numPerRow);
const c = i - r * numPerRow;
return `translate(${c * (sizeOfWaffle + paddingBetweenWaffles.x)},${
r * (sizeOfWaffle + paddingBetweenWaffles.y)
})`;
});

const cellSize = scale.bandwidth();

const cells = g
.append("g")
.selectAll("rect")
.data((d) => d)
.join("rect")
.attr("fill", (d) => (d.index === -1 ? "#ddd" : "#eeba0b"));

cells
.attr("x", (d) => scale(d.x))
.attr("y", (d) => scale(d.y))
.attr("width", cellSize)
.attr("height", cellSize);

g.append("text")
.attr(
"transform",
`translate(${(sizeOfWaffle + paddingBetweenWaffles.x) / 2 - 10}, ${
sizeOfWaffle + 25
})`
)
.attr("text-anchor", "middle")
.text((d, i) => `${data[i].category} - ${data[i].value}%`)
.attr("font-size", "11pt")
.attr("font-family", "Manrope")
.style("font-weight", "bold")
.style("fill", "black");

return svg.node();
}
Insert cell
margin = ({ top: 30, right: 100, bottom: 30, left: 100 })
Insert cell
scale = d3
.scaleBand()
.domain(d3.range(0, 10))
.range([0, sizeOfWaffle])
.padding(0.1)
Insert cell
paddingBetweenWaffles = ({ x: 20, y: 80 })
Insert cell
sizeOfWaffle = 180
Insert cell
width = 1200
Insert cell
height = 600
Insert cell
wafflesData = data.map((d, i) => {
let curr = 0;
let waffle = [];
for (let y = 9; y >= 0; y--) {
for (let x = 0; x < 10; x++) {
waffle.push({ x, y, index: curr < Math.round(d.value) ? i : -1 });
curr++;
}
}
return waffle;
})
Insert cell
data = [
{ category: "Doctor", value: 86 },
{ category: "Railway Worker", value: 83 },
{ category: "IT Worker", value: 81 },
{ category: "Business Person", value: 71 },
{ category: "Carpenter", value: 70 },
{ category: "Banker/City Worker", value: 68 },
{ category: "Scientist/Researcher", value: 65 },
{ category: "Actor", value: 64 },
{ category: "Lawyer", value: 60 },
{ category: "PR", value: 60 }
]
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more