liveBook · Manning

Legend

As explained in D3.js in Action, Third Edition

A legend is a chart component that maps visual encodings such as colors or symbols to the corresponding data categories or meanings.

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

How D3.js in Action, Third Edition covers it

How deep it goes
Builds a legend from HTML, D3 data binding, and CSS, stopping short of complex SVG text positioning.
Examples
Uses a stacked bar chart whose music formats become colored squares and labels in an HTML list.
What it assumes
Assumes a chart, a legend container, and category data with color and label values already exist.
What you can do after
Builds a chart legend from scratch with D3, HTML list elements, spans, and CSS layout.
How it connects
Connects legends to D3, ordinal scales, discrete color scales, HTML, CSS, and SVG.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.