Skip to main content
100%

d3 color-legend example

✓ Published0🌍 Public
Aackuser
Last edited May 6, 2020
Created on Dec 7, 2023

This example shows how to render a D3 ordinal color scale as a legend of colored swatches in a plain HTML page, using the `swatches` function from the Observable `@d3/color-legend` notebook. The color scale and margin values come from the stacked-area-chart example, with categories like “Manufacturing” and “Government” mapped to `d3.schemeCategory10`. It imports the Observable `Runtime` and loads the notebook’s cell via `module.value("swatches")`, then appends the returned DOM element to a container. The legend uses a fixed column width of 180 pixels.

AI-generated description

In response to a question on Twitter by @everybody_kurts:

“Hi @mbostock, I was looking at your stacked area chart at https://observablehq.com/@d3/stacked-area-chart. At the end of the file, you import swatches from "@d3/color-legend". I tried finding this on npmjs but to no avail. Is this exclusive to @observablehq only?”

This shows how to use the swatches function from the @d3/color-legend notebook in a plain HTML page. The example data for the swatches (the color scale and margin) is copied from the @d3/stacked-area-chart notebook.

Similar vizzes