Skip to content

Instantly share code, notes, and snippets.

@tophtucker
Last active February 21, 2024 22:11
Show Gist options
  • Save tophtucker/87f02769353208d625c4762a02a3ad55 to your computer and use it in GitHub Desktop.
Save tophtucker/87f02769353208d625c4762a02a3ad55 to your computer and use it in GitHub Desktop.
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 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.

<!DOCTYPE html>
<body>
<div class="container"></div>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script type="module">
// Import Observable runtime and the @d3/color-legend notebook
import {Runtime} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js";
import d3_colorLegend from "https://api.observablehq.com/@d3/color-legend.js?v=3";
// Example chart data copied from https://observablehq.com/@d3/stacked-area-chart
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"])
.range(d3.schemeCategory10)
const margin = ({top: 20, right: 30, bottom: 30, left: 40})
// Container element into which the swatches will render
const container = document.querySelector(".container")
renderSwatches(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"});
el.appendChild(element);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment