Skip to content

Commit

Permalink
standalone scales with Plot.scale (#639)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock authored Dec 31, 2021
1 parent 6f10b74 commit 72b2adb
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,12 @@ const color = plot.scale("color"); // retrieve the color scale object
console.log(color.range); // inspect the color scale’s range, ["red", "blue"]
```

You can also create a standalone scale with Plot.**scale**(*options*):

```js
const color = Plot.scale({color: {type: "linear"}});
```

To reuse a scale across plots, pass the scale object into another plot specification:

```js
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ export {window, windowX, windowY} from "./transforms/window.js";
export {selectFirst, selectLast, selectMaxX, selectMaxY, selectMinX, selectMinY} from "./transforms/select.js";
export {stackX, stackX1, stackX2, stackY, stackY1, stackY2} from "./transforms/stack.js";
export {formatIsoDate, formatWeekday, formatMonth} from "./format.js";
export {scale} from "./scales.js";
export {legend} from "./legends.js";
11 changes: 11 additions & 0 deletions src/scales.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,17 @@ export function coerceDate(x) {
: new Date(x);
}

export function scale(options = {}) {
let scale;
for (const key in options) {
if (!registry.has(key)) continue; // ignore unknown properties
if (scale !== undefined) throw new Error("ambiguous scale definition");
scale = exposeScale(normalizeScale(key, options[key]));
}
if (scale === undefined) throw new Error("invalid scale definition");
return scale;
}

export function exposeScales(scaleDescriptors) {
return key => {
if (!registry.has(key = `${key}`)) throw new Error(`unknown scale: ${key}`);
Expand Down
11 changes: 11 additions & 0 deletions test/scales/scales-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ import * as d3 from "d3";
import assert from "assert";
import it from "../jsdom.js";

it("Plot.scale(description) returns a standalone scale", () => {
const color = Plot.scale({color: {type: "linear"}});
scaleEqual(color, {
type: "linear",
domain: [0, 1],
range: [0, 1],
interpolate: d3.interpolateTurbo,
clamp: false
});
});

it("plot(…).scale(name) returns undefined for an unused scale", () => {
const plot = Plot.dot([1, 2], {x: d => d, y: d => d}).plot();
assert.deepStrictEqual(plot.scale("r"), undefined);
Expand Down

0 comments on commit 72b2adb

Please sign in to comment.