### Index --- # https://vitepress.dev/reference/default-theme-home-page layout: home titleTemplate: "The JavaScript library for exploratory data visualization" head: - - link - rel: canonical href: https://observablehq.com/plot/ - - meta - name: title content: Observable Plot - - meta - name: description content: The JavaScript library for exploratory data visualization - - meta - name: twitter:card content: summary_large_image - - meta - name: twitter:site content: "@observablehq" - - meta - property: og:description content: The JavaScript library for exploratory data visualization - - meta - property: og:image content: https://static.observableusercontent.com/thumbnail/64f414fef8a91248865f5759641b0cf537bc87c0aaf57dc368ffe673013eccaa.jpg - - meta - property: og:site_name content: Observable - - meta - property: og:title content: Observable Plot - - meta - property: og:type content: article - - meta - property: og:url content: https://observablehq.com/plot/ hero: name: "Observable Plot" text: "The JavaScript library for exploratory data visualization" tagline: "Create expressive charts with concise code" image: src: /plot.svg alt: Observable Plot actions: - theme: brand text: Get started link: /getting-started - theme: alt text: What is Plot? link: /what-is-plot - theme: alt text: Examples link: https://observablehq.com/@observablehq/plot-gallery features: - title: Marks details: "Plot doesn’t have chart types. Instead, it has layered geometric shapes such as bars, dots, and lines." link: /features/marks - title: Scales details: "Scales map an abstract value such as time or temperature to a visual value such as position or color." link: /features/scales - title: Transforms details: "Derive data on-the-fly while plotting, say to bin quantitative values or compute a rolling average." link: /features/transforms - title: Facets details: "Small multiples facilitate comparison by repeating a plot across partitions of data." link: /features/facets - title: Projections details: "Plot supports GeoJSON and D3’s spherical projection system for geographic maps." link: /features/projections - title: Built with D3 details: "Plot is built by the same team as D3. If you know some D3, you’ll be right at home with Plot." link: https://d3js.org linkText: Visit D3 - title: Plot without code details: With Observable’s chart cell, quickly create plots with a GUI, then eject to code to customize. link: https://observablehq.com/@observablehq/chart-cell linkText: Try chart cell - title: Built by Observable details: Plot is developed by Observable, the platform for collaborative data analysis. link: https://observablehq.com linkText: Visit Observable --- --- ### Api # API index ## Methods ## Options --- ### Community # Community 🏠 {#community} Learning Plot? Love data visualization? Don’t go it alone! Join our community to get help, be inspired, and do the same for others. ## Staying up-to-date :::tip Please star ⭐️ our [GitHub repo](https://github.com/observablehq/plot) to show your support for us on GitHub! ::: Plot is getting better all the time; catch up on [recent releases](https://github.com/observablehq/plot/releases) by reading our [CHANGELOG](https://github.com/observablehq/plot/blob/main/CHANGELOG.md). And of course, follow us on [Observable](https://observablehq.com/@observablehq?tab=profile), [Mastodon](https://vis.social/@observablehq), [Twitter](https://twitter.com/observablehq), and [LinkedIn](https://www.linkedin.com/company/observable)! ## Getting help We recommend asking for help on [GitHub discussions](https://github.com/observablehq/plot/discussions). We encourage you to share your work, no matter how messy, on [Observable](https://observablehq.com). Sharing live code is the easiest way to let people see what you see, and to debug your problem. Strive for a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) — it helps people hone in on your problem more quickly. When asking for help, don’t just post your code and ask people to fix it. Provide context, and say what you want help with. For example: - What are you trying to achieve? What is your goal? - What other solutions have you tried? - What behavior are you currently seeing? - Is the current behavior not what you expect? If you think you’ve found a bug in Plot, please file a [GitHub issue](https://github.com/observablehq/plot/issues). But don’t use an issue to ask for help — you’ll have better luck on the forum or Slack. ## Getting involved We’d love for you to join the community! Here are some ways to participate: * Share your work on [Observable](https://observablehq.com). Working in public is a great way to help others learn and be inspired. Don’t worry if your code is messy or unfinished; sharing drafts normalizes the challenges that everyone experiences doing data visualization. * Upvote 👍 or comment on [GitHub issues](https://github.com/observablehq/plot/issues). We’d love your input on what to build next. If your desired feature isn’t already there, or if you’ve found a bug, file an issue and tell us about it. * Answer questions or participate in discussions on [GitHub](https://github.com/observablehq/plot/discussions). You’ll help others, and might learn something yourself, too. * Join the [Observable community Slack](https://observablehq.com/slack/join) to meet others using Plot. * Open a pull request! Read our [guide to contributing](https://github.com/observablehq/plot/blob/main/CONTRIBUTING.md). Please help us maintain a positive environment for all by adhering to our [code of conduct](https://github.com/observablehq/.github/blob/master/CODE_OF_CONDUCT.md). Thank you! --- ### What Is Plot # What is Plot? **Observable Plot** is a free, open-source, JavaScript library for visualizing tabular data, focused on accelerating exploratory data analysis. It has a concise, memorable, yet expressive interface, featuring [scales](./features/scales.md) and [layered marks](./features/marks.md) in the *grammar of graphics* style popularized by [Leland Wilkinson](https://en.wikipedia.org/wiki/Leland_Wilkinson) and [Hadley Wickham](https://en.wikipedia.org/wiki/Hadley_Wickham) and inspired by the earlier ideas of [Jacques Bertin](https://en.wikipedia.org/wiki/Jacques_Bertin). And there are [plenty of examples](https://observablehq.com/@observablehq/plot-gallery) to learn from and copy-paste. In the spirit of *show don’t tell*, here’s a scatterplot of body measurements of athletes from the [2016 Summer Olympics](https://flother.is/2017/olympic-games-data/). :::plot defer https://observablehq.com/@observablehq/plot-olympians-scatterplot ```js Plot .dot(olympians, {x: "weight", y: "height", stroke: "sex"}) .plot({color: {legend: true}}) ``` ::: A plot specification assigns columns of data (*weight*, *height*, and *sex*) to visual properties of marks (**x**, **y**, and **stroke**). Plot does the rest! You can configure much more, if needed, but Plot’s goal is to help you get a meaningful visualization quickly to accelerate analysis. This scatterplot suffers from overplotting: many dots are drawn in the same spot, so it’s hard to perceive density. We can fix this by applying a [bin transform](./transforms/bin.md) to group athletes of similar height and weight (and sex), and then use opacity to encode the number of athletes in the bin. :::plot defer https://observablehq.com/@observablehq/plot-olympians-bins ```js Plot.rect(olympians, Plot.bin({fillOpacity: "count"}, {x: "weight", y: "height", fill: "sex", inset: 0})).plot() ``` ::: Or we could try the [density mark](./marks/density.md). :::plot defer https://observablehq.com/@observablehq/plot-olympians-density ```js Plot.density(olympians, {x: "weight", y: "height", stroke: "sex"}).plot() ``` ::: A simpler take on this data is to focus on one dimension: weight. We can use the bin transform again to make a histogram with weight on the *x*-axis and frequency on the *y*-axis. This plot uses a [rect mark](./marks/rect.md) and an implicit [stack transform](./transforms/stack.md). :::plot defer https://observablehq.com/@observablehq/plot-vertical-histogram ```js Plot.rectY(olympians, Plot.binX({y: "count"}, {x: "weight", fill: "sex"})).plot() ``` ::: Or if we’d prefer to show the two distributions separately as small multiples, we can [facet](./features/facets.md) the data along *y* (keeping the *fill* encoding for consistency, and adding grid lines and a rule at *y* = 0 to improve readability). :::plot defer https://observablehq.com/@observablehq/plot-faceted-histogram ```js Plot.plot({ grid: true, marks: [ Plot.rectY(olympians, Plot.binX({y: "count"}, {x: "weight", fill: "sex", fy: "sex"})), Plot.ruleY([0]) ] }) ``` ::: ## What can Plot do? Because marks are composable, and because you can extend Plot with custom marks, you can make almost anything with it — much more than the charts above! The following [tree diagram](./marks/tree.md) of the documentation gives a sense of what’s ”in the box” with Plot. Peruse our [gallery of examples](https://observablehq.com/@observablehq/plot-gallery) for more inspiration. --- ### Why Plot # Why Plot? **Observable Plot** is for exploratory data visualization. It’s for finding insights quickly. Its API, while expressive and configurable, optimizes for conciseness and memorability. We want the time to first chart to be as fast as possible. And the speed doesn’t stop there: Plot helps you quickly pivot and refine your views of data. Our hope with Plot is that you’ll spend less time reading the docs, searching for code to copy-paste, and debugging — and more time asking questions of data. Compared to other visualization tools, including low-level tools such as D3 and less expressive high-level tools such as chart templates, we think you’ll be more productive exploring data with Plot. You’ll spend more time “using vision to think” and less time wrangling the machinery of programming. Or put more simply: **with Plot, you’ll see more charts.** ## Plot is concise You can make a meaningful chart in Plot with as little as one line of code. :::plot https://observablehq.com/@observablehq/color-scatterplot ```js Plot.dot(penguins, {x: "culmen_length_mm", y: "culmen_depth_mm", stroke: "species"}).plot() ``` ::: What makes Plot concise? In a word: *defaults*. If you specify the semantics — your data and the desired encodings — Plot will figure out the rest. The beauty of defaults is that you can override them as needed. This is ideal for exploring: you invest minimally in the initial chart, and as you start to see something interesting, you progressively customize to improve the display. Perhaps the plot above would be easier to read with an aspect ratio proportional to the data, a grid, and a legend? :::plot https://observablehq.com/@observablehq/plot-refined-color-scatterplot ```js Plot.plot({ grid: true, aspectRatio: 1, inset: 10, x: {tickSpacing: 80, label: "Culmen length (mm)"}, y: {tickSpacing: 80, label: "Culmen depth (mm)"}, color: {legend: true}, marks: [ Plot.frame(), Plot.dot(penguins, {x: "culmen_length_mm", y: "culmen_depth_mm", stroke: "species"}) ] }) ``` ::: ## Plot transforms data Munging data, not visualizing it, is often most of the work of data analysis. Plot’s [transforms](./features/transforms.md) let you aggregate and derive data *within* your plot specification, reducing the time spent preparing data. For example, if you have a dataset of penguins, you can quickly count their frequency by *species* with the [group transform](./transforms/group.md). :::plot https://observablehq.com/@observablehq/plot-groupy-transform ```js Plot.plot({ marginLeft: 80, marginRight: 80, marks: [ Plot.barX(penguins, Plot.groupY({x: "count"}, {y: "species"})), Plot.ruleX([0]) ] }) ``` ::: Because transforms are integrated into Plot, they work automatically with other Plot features such as [faceting](./features/facets.md). For example, to breakdown the chart above by *island*, we just add the **fy** (vertical facet) option. :::plot https://observablehq.com/@observablehq/plot-groupy-transform/2 ```js Plot.plot({ marginLeft: 80, marginRight: 80, marks: [ Plot.barX(penguins, Plot.groupY({x: "count"}, {fy: "island", y: "species"})), Plot.ruleX([0]) ] }) ``` ::: And to color by *sex*, too? Add **fill**; the [bar mark](./marks/bar.md) then applies an implicit [stack transform](./transforms/stack.md). :::plot https://observablehq.com/@observablehq/plot-groupy-transform/3 ```js Plot.plot({ marginLeft: 80, marginRight: 80, color: {legend: true}, marks: [ Plot.barX(penguins, Plot.groupY({x: "count"}, {fy: "island", y: "species", fill: "sex"})), Plot.ruleX([0]) ] }) ``` ::: Plot’s transforms can do powerful things, including [normalizing series](./transforms/normalize.md), computing [moving averages](./transforms/window.md), laying out [trees](./marks/tree.md), [dodging](./transforms/dodge.md), and [hexagonal binning](./transforms/hexbin.md). ## Plot is composable Simple components gain power through composition, such as layering multiple [marks](./features/marks.md) into a single plot. Plot makes it easy to define custom composite marks, such as this one comprising a rule, area, and line: ```js function arealineY(data, {color, fillOpacity = 0.1, ...options} = {}) { return Plot.marks( Plot.ruleY([0]), Plot.areaY(data, {fill: color, fillOpacity, ...options}), Plot.lineY(data, {stroke: color, ...options}) ); } ``` You can use this composite mark like any built-in mark: :::plot https://observablehq.com/@observablehq/plot-arealiney-custom-mark ```js arealineY(aapl, {x: "Date", y: "Close", color: "blue"}).plot() ``` ::: Plot uses this technique internally: the [axis mark](./marks/axis.md) and [box mark](./marks/box.md) are both composite marks. :::plot https://observablehq.com/@observablehq/plot-penguins-horizontal-box-plot ```js Plot.boxX(penguins, {x: "body_mass_g", y: "species"}).plot({marginLeft: 60, y: {label: null}}) ``` ::: Plot’s [transforms](./features/transforms.md) are composable, too: to apply multiple transforms, you simply pass the *options* from one transform to the next. Some marks even apply implicit transforms, say for [stacking](./transforms/stack.md) or [binning](./transforms/bin.md) as shown [above](#plot-transforms-data). Mark options are plain JavaScript objects, so you can also share options across marks and inspect them to debug. ## Plot is extensible Plot isn’t a new language; it’s “just” vanilla JavaScript. Plot embraces JavaScript, letting you plug in your own functions for accessors, reducers, transforms… even custom marks! And Plot generates SVG, so you can style it with CSS and manipulate it just like you do with D3. (See [Mike Freeman’s tooltip plugin](https://observablehq.com/@mkfreeman/plot-tooltip) for a great example of extending Plot this way.) ## Plot builds on D3 Plot is informed by our more than [ten years’ experience](https://observablehq.com/@mbostock/10-years-of-open-source-visualization) developing [D3](https://d3js.org), the web’s most popular library for data visualization. Plot uses D3 to implement a wide variety of features: - scales (ticks, color schemes, number formatting) - shapes (areas, lines, curves, symbols, stacks) - planar geometry (Delaunay, Voronoi, contours, density estimation) - spherical geometry (geographic projections) - data manipulation (group, rollup, bin, statistics) - tree diagrams - … and more! If you already know some D3, you’ll find many parts of Plot familiar. We’ve long said that *D3 makes things possible, not necessarily easy.* And that’s true regardless of the task at hand. D3 makes hard and amazing things *possible*, yes, but even simple things that should be easy are often not. To paraphrase Amanda Cox: “Use D3 if you think it’s perfectly normal to write a hundred lines of code for a bar chart.” **Plot’s goal is to make the easy things easy, and fast, and then some.** :::tip Whether or not Plot succeeds at this goal is up to you — so we’d love [your feedback](https://github.com/observablehq/plot/discussions/new/choose) on what you find easy or hard to do with Plot. And we encourage you to [ask for help](https://github.com/observablehq/plot/discussions/categories/q-a) when you get stuck. We learn a lot from helping! ::: Since Plot and D3 have different goals, they make different trade-offs. Plot is more efficient: you can make charts quickly. But it is also necessarily less expressive: bespoke visualizations with extensive animation and interaction, advanced techniques like force-directed graph layout, or even developing your own charting library, are better done with D3’s low-level API. We recommend D3 for *bespoke* data visualizations, if you decide the extra expressiveness of D3 is worth the time and effort. D3 makes sense for media organizations such as *The New York Times* or *The Pudding*, where a single graphic may be seen by a million readers, and where a team of editors can work together to advance the state of the art in visual communication; but is it the best tool for building your team’s private dashboard, or a one-off analysis? You may be surprised how far you can get with Plot. --- ### .Vitepress/Config.Ts import {fileURLToPath, URL} from "node:url"; import path from "node:path"; import {defineConfig} from "vitepress"; import plot from "./markdown-it-plot.js"; // https://vitepress.dev/reference/site-config // prettier-ignore export default defineConfig({ title: "Plot", description: "The JavaScript library for exploratory data visualization", appearance: "force-auto", base: "/plot/", cleanUrls: true, vite: { resolve: { alias: [ {find: "@observablehq/plot", replacement: path.resolve("./src/index.js")}, {find: /^.*\/VPFooter\.vue$/, replacement: fileURLToPath(new URL("./theme/CustomFooter.vue", import.meta.url))} ] }, define: { __APP_VERSION__: JSON.stringify(process.env.npm_package_version) } }, vue: { template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith("observable-") } } }, markdown: { config: (md) => { plot(md); } }, head: [ ["link", {rel: "preconnect", href: "https://fonts.gstatic.com", crossorigin: ""}], ["link", {rel: "preload", as: "style", href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Spline+Sans+Mono:ital,wght@0,300..700;1,300..700&display=swap"}], ["link", {rel: "stylesheet", href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Spline+Sans+Mono:ital,wght@0,300..700;1,300..700&display=swap"}], ["link", {rel: "apple-touch-icon", href: "https://static.observablehq.com/favicon-512.0667824687f99c942a02e06e2db1a060911da0bf3606671676a255b1cf97b4fe.png"}], ["link", {rel: "icon", type: "image/png", href: "https://static.observablehq.com/favicon-512.0667824687f99c942a02e06e2db1a060911da0bf3606671676a255b1cf97b4fe.png", sizes: "512x512"}], ["script", {async: "", src: "https://www.googletagmanager.com/gtag/js?id=G-9B88TP6PKQ"}], ["script", {}, "window.dataLayer=window.dataLayer||[];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js',new Date());\ngtag('config','G-9B88TP6PKQ');"], ["script", {async: "", defer: "", src: "https://static.observablehq.com/assets/components/observable-made-by.js"}], ], sitemap: { hostname: "https://observablehq.com/plot/" }, themeConfig: { // https://vitepress.dev/reference/default-theme-config // Theme related configurations. logo: { light: "/observable-light.svg", dark: "/observable-dark.svg" }, sidebar: [ { text: "Introduction", items: [ {text: "What is Plot?", link: "/what-is-plot"}, {text: "Why Plot?", link: "/why-plot"}, {text: "Getting started", link: "/getting-started"}, {text: "Examples", link: "https://observablehq.com/@observablehq/plot-gallery"} ] }, { text: "Features", collapsed: false, items: [ {text: "Plots", link: "/features/plots"}, {text: "Marks", link: "/features/marks"}, {text: "Scales", link: "/features/scales"}, {text: "Projections", link: "/features/projections"}, {text: "Transforms", link: "/features/transforms"}, {text: "Interactions", link: "/features/interactions"}, {text: "Facets", link: "/features/facets"}, {text: "Legends", link: "/features/legends"}, {text: "Curves", link: "/features/curves"}, {text: "Formats", link: "/features/formats"}, {text: "Intervals", link: "/features/intervals"}, {text: "Markers", link: "/features/markers"}, {text: "Shorthand", link: "/features/shorthand"}, {text: "Accessibility", link: "/features/accessibility"} ] }, { text: "Marks", collapsed: true, items: [ {text: "Area", link: "/marks/area"}, {text: "Arrow", link: "/marks/arrow"}, {text: "Auto", link: "/marks/auto"}, {text: "Axis", link: "/marks/axis"}, {text: "Bar", link: "/marks/bar"}, {text: "Bollinger", link: "/marks/bollinger"}, {text: "Box", link: "/marks/box"}, {text: "Cell", link: "/marks/cell"}, {text: "Contour", link: "/marks/contour"}, {text: "Delaunay", link: "/marks/delaunay"}, {text: "Density", link: "/marks/density"}, {text: "Difference", link: "/marks/difference"}, {text: "Dot", link: "/marks/dot"}, {text: "Frame", link: "/marks/frame"}, {text: "Geo", link: "/marks/geo"}, {text: "Grid", link: "/marks/grid"}, {text: "Hexgrid", link: "/marks/hexgrid"}, {text: "Image", link: "/marks/image"}, {text: "Line", link: "/marks/line"}, {text: "Linear regression", link: "/marks/linear-regression"}, {text: "Link", link: "/marks/link"}, {text: "Raster", link: "/marks/raster"}, {text: "Rect", link: "/marks/rect"}, {text: "Rule", link: "/marks/rule"}, {text: "Text", link: "/marks/text"}, {text: "Tick", link: "/marks/tick"}, {text: "Tip", link: "/marks/tip"}, {text: "Tree", link: "/marks/tree"}, {text: "Vector", link: "/marks/vector"}, {text: "Waffle", link: "/marks/waffle"} ] }, { text: "Transforms", collapsed: true, items: [ {text: "Bin", link: "/transforms/bin"}, {text: "Centroid", link: "/transforms/centroid"}, {text: "Dodge", link: "/transforms/dodge"}, {text: "Filter", link: "/transforms/filter"}, {text: "Group", link: "/transforms/group"}, {text: "Hexbin", link: "/transforms/hexbin"}, {text: "Interval", link: "/transforms/interval"}, {text: "Map", link: "/transforms/map"}, {text: "Normalize", link: "/transforms/normalize"}, {text: "Select", link: "/transforms/select"}, {text: "Shift", link: "/transforms/shift"}, {text: "Sort", link: "/transforms/sort"}, {text: "Stack", link: "/transforms/stack"}, {text: "Tree", link: "/transforms/tree"}, {text: "Window", link: "/transforms/window"} ] }, { text: "Interactions", collapsed: true, items: [ {text: "Crosshair", link: "/interactions/crosshair"}, {text: "Pointer", link: "/interactions/pointer"} ] }, {text: "API index", link: "/api"} ], search: { provider: "local" }, footer: { message: "Library released under ISC License.", copyright: `Copyright 2020–${new Date().getUTCFullYear()} Observable, Inc.` } } }); --- ### CONTRIBUTING # Observable Plot - Contributing Observable Plot is open source and released under the [ISC license](./LICENSE). You are welcome to [send us pull requests](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) to contribute bug fixes or new features. We also invite you to participate in [issues](https://github.com/observablehq/plot/issues) and [discussions](https://github.com/observablehq/plot/discussions). We use issues to track and diagnose bugs, as well as to debate and design enhancements to Plot. Discussions are intended for you to ask for help using Plot, or to share something cool you’ve built with Plot. You can also ask for help on the [Observable Forum](https://talk.observablehq.com) and the [Observable community Slack](https://observablehq.com/slack/join). We request that you abide by our [code of conduct](https://observablehq.com/@observablehq/code-of-conduct) when contributing and participating in discussions. ## Development To contribute to Observable Plot, you’ll need a local development environment to make and test changes to Plot’s source code. To get started, follow GitHub’s tutorial on [forking (and cloning) a repository](https://docs.github.com/en/get-started/quickstart/fork-a-repo). Once you’ve cloned your fork of the Plot repository, open a terminal and `cd` in your forked repository. Then run Yarn to install dependencies: ```bash pnpm install ``` You may encounter an error installing [node-canvas](https://github.com/Automattic/node-canvas), such as: ``` node-pre-gyp ERR! install response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.9.1/canvas-v2.9.1-node-v93-darwin-unknown-arm64.tar.gz node-pre-gyp WARN Pre-built binaries not installable for canvas@2.9.1 and node@16.15.0 (node-v93 ABI, unknown) (falling back to source compile with node-gyp) node-pre-gyp WARN Hit error response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.9.1/canvas-v2.9.1-node-v93-darwin-unknown-arm64.tar.gz ``` If this happens, you will need to [compile node-canvas from source](https://github.com/Automattic/node-canvas/blob/master/Readme.md#compiling). On macOS you can use Homebrew to install the needed dependencies: ```bash brew install pkg-config cairo pango libpng jpeg giflib librsvg ``` ## Testing After making changes to Plot’s source code, run Plot’s test suite to verify that your code is doing what you expect and that you haven’t introduced any other unexpected changes in behavior. Plot has two types of tests: **unit tests** and **snapshot tests**. Tests are run automatically on pull requests (via GitHub Actions), but you’ll want to run them locally to verify your changes before opening a pull request. To run the tests: ```bash pnpm run test ``` This will also run ESLint on Plot’s source to help catch simple mistakes, such as unused imports. Please run Prettier before submitting any pull request. Check “format on save” in your code editor, or run: ```bash pnpm exec prettier --write . ``` A test coverage report can be generated with [c8](https://github.com/bcoe/c8), in text and lcov formats, to help you identify which lines of code are not (yet!) covered by tests. Just run: ```bash pnpm run test:coverage ``` ### Unit tests Unit tests live in `test` and have the `-test.js` file extension; see [`test/marks/area-test.js`](./test/marks/area-test.js) for example. Generally speaking, unit tests make specific, low-level assertions about the behavior of Plot’s API, including internals and helper methods. If you add a new feature, or change the behavior of an existing feature, please update the unit tests so that we can more easily maintain your contribution into the future. For example, here’s a unit test that tests how Plot formats months: ```js it("formatMonth(locale, format) does the right thing", () => { assert.strictEqual(Plot.formatMonth("en", "long")(0), "January"); assert.strictEqual(Plot.formatMonth("en", "short")(0), "Jan"); assert.strictEqual(Plot.formatMonth("en", "narrow")(0), "J"); }); ``` Plot’s unit tests are written with [Mocha](https://mochajs.org). If you like, you can also run Mocha in watch mode for a specific file, so that unit tests re-run automatically when you make changes. For example: ```bash pnpm run test:vitest test/marks/bar-test.js ``` ### Snapshot tests Snapshot tests live in `test/plots` and are registered in [`test/plots/index.ts`](./test/plots/index.ts); see [`test/plots/aapl-bollinger.ts`](./test/plots/aapl-bollinger.ts) for example. Unlike unit tests which only test individual methods, snapshot tests actually visualize data—they’re more representative of how we expect people will use Plot. Snapshot tests can also serve as examples of how to use the Plot API, though note that some of the examples intentionally test edge case of the API and may not embody best practices. Each snapshot test defines a plot by exporting a default async function. For example, here’s a line chart using BLS unemployment data: ```ts import * as Plot from "@observablehq/plot"; import * as d3 from "d3"; export async function lineUnemployment() { const bls = await d3.csv("data/bls-metro-unemployment.csv", d3.autoType); return Plot.plot({ marks: [ Plot.ruleY([0]), Plot.lineY(bls, {x: "date", y: "unemployment", z: "division"}) ] }); } ``` When a snapshot test is run, its output is compared against the SVG or HTML snapshot saved in the `test/output` folder. This makes it easier to review the effect of code changes and to catch unintended changes. Snapshot tests must have deterministic, reproducible behavior; they should not depend on live data, external servers, the current time, the weather, etc. To use randomness in a test, use a seeded random number generator such as [d3.randomLcg](https://d3js.org/d3-random#randomLcg). To add a new snapshot test, create a new JavaScript file in the `test/plots` folder using the pattern shown above. Then export your snapshot test function from [`test/plots/index.ts`](./test/plots/index.ts). For example: ```js export * from "./moby-dick.ts"; ``` The best thing about snapshot tests is that you can see the live result in your browser as you make changes to Plot’s source code! This lets you immediately assess visually what Plot is doing. To preview snapshot tests during development, Plot uses [Vite](https://vitejs.dev). To start Vite: ```bash pnpm run dev ``` This will open http://localhost:8008/ in your browser where you can choose a snapshot test. As you edit the source, the current test will update live in your browser as you save changes. You can change the selected test from the drop-down menu. When the drop-down menu is focused, the left and right arrow keys cycle between tests. When previewing snapshot tests, consider using your browser’s debugger or element inspector to assist development. Running Plot’s snapshot tests will automatically generate any missing snapshots in `test/output`. You should `git add` these before committing your changes. (If you forget, your PR will fail in CI, and you’ll get a reminder.) Changed snapshots are saved alongside the originals with a `-changed` suffix for visual inspection. If your code intentionally changes some of the existing snapshots, simply blow away the existing snapshots and run the tests again. You can then review what’s changed using `git diff`. ``` rm -rf test/output pnpm run test:vitest ``` ## Documentation When submitting a pull request, please remember to update Plot’s documentation to reflect changes to the public API. You are also welcome to edit Plot’s [CHANGELOG.md](./CHANGELOG.md) to assist with writing future release notes. In addition, please reference any related [issues](https://github.com/observablehq/plot/issues) (or discussions) in your pull request description. If you’d like to share a live demonstration or motivating example of your change to Plot, you can regenerate Plot’s release bundle like so: ```bash pnpm run prepublishOnly ``` The generated bundle `dist/plot.umd.js` can then be loaded like so: ```html ``` Alternatively, you can attach the `dist/plot.umd.js` file to an [Observable notebook](https://observablehq.com), and then load it like so: ```js Plot = require(await FileAttachment("plot.umd.js").url()) ``` --- ### CHANGELOG # Observable Plot - Changelog Year: **Current (2025)** · [2024](./CHANGELOG-2024.md) · [2023](./CHANGELOG-2023.md) · [2022](./CHANGELOG-2022.md) · [2021](./CHANGELOG-2021.md) ## 0.6.17 [Released February 14, 2025.](https://github.com/observablehq/plot/releases/tag/v0.6.17) The [**clip** mark option](https://observablehq.com/plot/features/marks#clip) now supports GeoJSON objects 🌎 in addition to the named *frame* and *sphere* clipping methods, allowing the visual extent of marks to be limited to arbitrary polygons. For instance, this Voronoi mesh of world airports is clipped to land boundaries: [a map of world airports with a Voronoi mesh clipped to land](https://observablehq.com/@observablehq/plot-world-airports) ```js Plot.plot({ projection: {type: "orthographic", rotate: [110, -50]}, marks: [ Plot.dot(airports, {x: "longitude", y: "latitude", fill: "red", r: 1}), Plot.voronoiMesh(airports, {x: "longitude", y: "latitude", clip: land}), Plot.sphere(), Plot.geo(land) ] }) ``` The GeoJSON object passed to the **clip** option is rendered as a [`clipPath` element](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath) using the same path data that a [geo mark](https://observablehq.com/plot/marks/geo) would produce, respecting the plot’s top-level **projection** option, if any. For performance, `clipPath` elements are shared by marks clipped with the same GeoJSON object. For example, the [raster mark](https://observablehq.com/plot/marks/raster) and [contour mark](https://observablehq.com/plot/marks/contour) below show atmospheric water vapor measurements across the United States from [NASA Earth Observations](https://neo.gsfc.nasa.gov/view.php?datasetId=MYDAL2_M_SKY_WV); both marks are clipped to the nation’s boundary, censoring the (absurd) values that would otherwise be interpolated between Alaska, Southern California, and Hawai’i. [a map of water vapor measurements in the United States](https://observablehq.com/@observablehq/plot-us-water-vapor) ```js Plot.raster(vapor, { fill: Plot.identity, width: 360, height: 180, x1: -180, y1: 90, x2: 180, y2: -90, interpolate: "barycentric", blur: 10, clip: nation }).plot() ``` [The code for the map above is too long to reproduce here in its entirety; click the image above for the complete code.] The **clip** mark option can also be used to clip against arbitrary polygons, not just geographic boundaries. For example, to show the value of [Math.atan2](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) over the unit circle: [the value of atan2 across the unit disc, encoded as color](https://observablehq.com/@observablehq/plot-color-angle) ```js Plot.raster({ x1: -1, x2: 1, y1: -1, y2: 1, fill: (x, y) => Math.atan2(y, x), clip: { type: "Polygon", coordinates: [ d3.range(0, 2 * Math.PI, 0.1).map((angle) => [Math.cos(angle), Math.sin(angle)]) ] } }).plot({width: 300, aspectRatio: 1}) ``` The interactive **tip** associated with a [waffle mark](https://observablehq.com/plot/marks/waffle) is now anchored to the “center” of the visual representation of the associated datum. That center depends on the shape that is referenced. For fun, here’s a chart from our unit tests showing these anchoring points for various amounts of waffling. Baffling! waffle mark with the anchor position of each datum marked with its value --- For earlier changes, continue to the [2024 CHANGELOG](./CHANGELOG-2024.md). ---