Skip to content

Commit 295942e

Browse files
committed
scale:legend option
accepts a function that receives the scale; if that function returns a DOM node, adds it to the figure.
1 parent 85ae2c2 commit 295942e

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

src/plot.js

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,7 @@ export function plot(options = {}) {
9191
if (node != null) svg.appendChild(node);
9292
}
9393

94-
const figure = wrap(svg, {caption});
95-
figure.scales = (key) => exposeScales(scaleDescriptors, key);
96-
return figure;
94+
return wrap(svg, scaleDescriptors, {caption});
9795
}
9896

9997
function Dimensions(
@@ -144,11 +142,25 @@ function autoHeight({y, fy, fx}) {
144142
}
145143

146144
// Wrap the plot in a figure with a caption, if desired.
147-
function wrap(svg, {caption}) {
148-
if (caption == null) return svg;
149-
const figure = document.createElement("figure");
150-
figure.appendChild(svg);
151-
const figcaption = figure.appendChild(document.createElement("figcaption"));
152-
figcaption.appendChild(caption instanceof Node ? caption : document.createTextNode(caption));
153-
return figure;
145+
function wrap(svg, scaleDescriptors, {caption} = {}) {
146+
const scales = (key) => exposeScales(scaleDescriptors, key);
147+
const legends = [];
148+
for (let key in scaleDescriptors) {
149+
const {legend} = scaleDescriptors[key];
150+
if (typeof legend === "function") {
151+
const l = legend(scales(key));
152+
if (l instanceof Node) legends.push(l);
153+
}
154+
}
155+
if (caption == null && legends.length === 0) {
156+
return svg.scales = scales, svg;
157+
}
158+
const figure = create("figure");
159+
for (const legend of legends) figure.append(() => legend);
160+
figure.append(() => svg);
161+
if (caption != null) {
162+
figure.append("figcaption")
163+
.append(() => caption instanceof Node ? caption : document.createTextNode(caption));
164+
}
165+
return Object.assign(figure.node(), {scales});
154166
}

src/scales.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,10 @@ function Scale(key, channels = [], options = {}) {
7575
case undefined: break;
7676
default: throw new Error(`unknown scale type: ${options.type}`);
7777
}
78-
if (scale) scale.scale.type = type;
78+
if (scale) {
79+
if (options.legend) scale.legend = options.legend;
80+
scale.scale.type = type;
81+
}
7982
return scale;
8083
}
8184

0 commit comments

Comments
 (0)