A legend maps visual encodings, such as colors or symbols, to the data categories they represent. In a chart, it helps readers interpret what they see. section 5.3
For a color legend, use traditional HTML instead of drawing every label and colored square in SVG. An unordered list provides the structure: each list item contains one span for the color and another for its label. section 5.3
Build a D3 color legend in three steps:
- Select the existing legend container, append a <ul>, and assign it a color-legend class. section 5.3
- Bind the formatsInfo array and join one <li> element for each data category. section 5.3
- Append a color span using the category color, then append a label span using the category label. section 5.3
- Use CSS flex layout, wrapping, spacing, and inline-block spans to position the legend below the chart. section 5.3
Color legend for a stacked bar chart
A stacked bar chart can place a color legend below the chart. Each music format in formatsInfo becomes a list item with a colored square and its corresponding label. section 5.3
const legendItems = d3.select(".legend-container")
.append("ul") #1
.attr("class", "color-legend")
.selectAll(".color-legend-item")
.data(formatsInfo)
.join("li")
.attr("class", "color-legend-item");
legendItems #2
.append("span")
.attr("class", "color-legend-item-color")
.style("background-color", d => d.color);
legendItems #3
.append("span")
.attr("class", "color-legend-item-label")
.text(d => d.label);
This implementation shows the complete D3 data-binding pattern for creating legend items, their color spans, and their labels. section 5.3
