Published
Edited
May 20, 2020
1 fork
5 stars
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr("width", 400)
.attr("height", 400)
// Legend as a group
const legend = svg.append("g")
// Apply a translation to the entire group
.attr("transform", "translate(100, 100)")
const size = 20;
const border_padding = 15;
const item_padding = 5;
const text_offset = 2;
// Border
legend
.append('rect')
.attr("width", 120)
.attr("height", 125)
.style("fill", "none")
.style("stroke-width", 1)
.style("stroke", "black");
// Boxes
legend.selectAll("boxes")
.data(domains)
.enter()
.append("rect")
.attr("x", border_padding)
.attr("y", (d, i) => border_padding + (i * (size + item_padding)))
.attr("width", size)
.attr("height", size)
.style("fill", (d) => color(d));
// Labels
legend.selectAll("labels")
.data(domains)
.enter()
.append("text")
.attr("x", border_padding + size + item_padding)
.attr("y", (d, i) => border_padding + i * (size + item_padding) + (size / 2) + text_offset)
// .style("fill", (d) => color(d))
.text((d) => d)
.attr("text-anchor", "left")
.style("alignment-baseline", "middle")
.style("font-family", "sans-serif");
return svg.node();
}
Insert cell
palette = ["#f58442", "#ede02d", "#9fbda2", "#6dbfd6"];
Insert cell
domains = ["Phase 1", "Phase 2", "Phase 3", "Phase 4"];
Insert cell
color = d3.scaleOrdinal(palette).domain(domains);
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