Skip to content

Commit 72b2adb

Browse files
authored
standalone scales with Plot.scale (#639)
1 parent 6f10b74 commit 72b2adb

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,12 @@ const color = plot.scale("color"); // retrieve the color scale object
212212
console.log(color.range); // inspect the color scale’s range, ["red", "blue"]
213213
```
214214

215+
You can also create a standalone scale with Plot.**scale**(*options*):
216+
217+
```js
218+
const color = Plot.scale({color: {type: "linear"}});
219+
```
220+
215221
To reuse a scale across plots, pass the scale object into another plot specification:
216222

217223
```js

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ export {window, windowX, windowY} from "./transforms/window.js";
2323
export {selectFirst, selectLast, selectMaxX, selectMaxY, selectMinX, selectMinY} from "./transforms/select.js";
2424
export {stackX, stackX1, stackX2, stackY, stackY1, stackY2} from "./transforms/stack.js";
2525
export {formatIsoDate, formatWeekday, formatMonth} from "./format.js";
26+
export {scale} from "./scales.js";
2627
export {legend} from "./legends.js";

src/scales.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,17 @@ export function coerceDate(x) {
309309
: new Date(x);
310310
}
311311

312+
export function scale(options = {}) {
313+
let scale;
314+
for (const key in options) {
315+
if (!registry.has(key)) continue; // ignore unknown properties
316+
if (scale !== undefined) throw new Error("ambiguous scale definition");
317+
scale = exposeScale(normalizeScale(key, options[key]));
318+
}
319+
if (scale === undefined) throw new Error("invalid scale definition");
320+
return scale;
321+
}
322+
312323
export function exposeScales(scaleDescriptors) {
313324
return key => {
314325
if (!registry.has(key = `${key}`)) throw new Error(`unknown scale: ${key}`);

test/scales/scales-test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,17 @@ import * as d3 from "d3";
33
import assert from "assert";
44
import it from "../jsdom.js";
55

6+
it("Plot.scale(description) returns a standalone scale", () => {
7+
const color = Plot.scale({color: {type: "linear"}});
8+
scaleEqual(color, {
9+
type: "linear",
10+
domain: [0, 1],
11+
range: [0, 1],
12+
interpolate: d3.interpolateTurbo,
13+
clamp: false
14+
});
15+
});
16+
617
it("plot(…).scale(name) returns undefined for an unused scale", () => {
718
const plot = Plot.dot([1, 2], {x: d => d, y: d => d}).plot();
819
assert.deepStrictEqual(plot.scale("r"), undefined);

0 commit comments

Comments
 (0)