Skip to content

Instantly share code, notes, and snippets.

Last active May 7, 2021 16:32
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
d3 color-legend example

In response to a question on Twitter by @everybody_kurts:

“Hi @mbostock, I was looking at your stacked area chart at 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.

<!DOCTYPE html>
<div class="container"></div>
<script src=""></script>
<script type="module">
// Import Observable runtime and the @d3/color-legend notebook
import {Runtime} from "";
import d3_colorLegend from "";
// Example chart data copied from
const color = d3.scaleOrdinal()
.domain(["Wholesale and Retail Trade","Manufacturing","Leisure and hospitality","Business services","Construction","Education and Health","Government","Finance","Self-employed","Other","Transportation and Utilities","Information","Agriculture","Mining and Extraction"])
const margin = ({top: 20, right: 30, bottom: 30, left: 40})
// Container element into which the swatches will render
const container = document.querySelector(".container")
async function renderSwatches(el) {
// Get the value of the "swatches" notebook cell, which is the function we want, which returns a DOM element
const module = new Runtime().module(d3_colorLegend);
const swatches = await module.value("swatches");
// Finally, call `swatches` with our options and append it to the container
const element = swatches({color, marginLeft: margin.left, columns: "180px"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment