Skip to content

Commit 228565b

Browse files
committed
The plot's scales object contains the minimum set of options that can be used to recreate the scale in another plot. In particular it doesn't show the (D3) scale anymore. Instead, a convenience function Plot.scale(options) is provided, that will turn a scale *options* object into a D3 scale, ready to use in another context. (This also clears the question of mutability.)
1 parent 4169fcf commit 228565b

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

README.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,21 +200,24 @@ Plot.plot({
200200
})
201201
```
202202

203-
All the scales are exposed as the *scales* property of the plot. We recommend using *scale*.copy if making any use of these scales that might mutate them.
203+
All the scale definitions are exposed as the *scales* property of the plot.
204204

205205
```js
206206
color = Plot.plot({…}).scales.color;
207-
color.range() // ["red", "blue"]
207+
color.range // ["red", "blue"]
208208
```
209209

210210
And, to reuse the scale in another plot:
211211

212212
```js
213+
const plot1 = Plot.plot(…);
214+
213215
Plot.plot({
214-
color: { domain: color.copy().domain(), range: color.copy().range() }
216+
color: plot:.scales.color
215217
})
216218
```
217219

220+
Plot.*scale*(*options*) returns a [D3 scale](https://github.com/d3/d3-scale) that matches the Plot *options* object.
218221

219222
### Position options
220223

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export {plot} from "./plot.js";
22
export {Mark, valueof} from "./mark.js";
3+
export {scale} from "./scales.js";
34
export {Area, area, areaX, areaY} from "./marks/area.js";
45
export {BarX, BarY, barX, barY} from "./marks/bar.js";
56
export {Cell, cell, cellX, cellY} from "./marks/cell.js";

src/scales.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ function Scale(key, channels = [], options = {}) {
8282
return scale;
8383
}
8484

85+
export function scale(options) {
86+
return Scale(undefined, undefined, options).scale;
87+
}
88+
8589
function inferScaleType(key, channels, {type, domain, range}) {
8690
if (key === "fx" || key === "fy") return "band";
8791
if (type !== undefined) {
@@ -128,7 +132,6 @@ function exposeScale({scale, label}) {
128132
...scale.interpolate && {interpolate: scale.interpolate()},
129133
...label !== undefined && {label},
130134
...scale.type && {type: scale.type},
131-
...scale.clamp && scale.clamp() && {clamp: true},
132-
scale
135+
...scale.clamp && scale.clamp() && {clamp: true}
133136
};
134137
}

0 commit comments

Comments
 (0)