From bc7486e7d93bbc6f75340c01d31253bb0653b0a5 Mon Sep 17 00:00:00 2001 From: Mike Bostock Date: Thu, 15 Dec 2022 13:59:40 -0800 Subject: [PATCH] fix descending domains on diverging scales --- src/scales/diverging.js | 2 ++ test/scales/scales-test.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/scales/diverging.js b/src/scales/diverging.js index 0e020937bb..b111f9d3dd 100644 --- a/src/scales/diverging.js +++ b/src/scales/diverging.js @@ -1,4 +1,5 @@ import { + descending, interpolateNumber, interpolateRgb, piecewise, @@ -37,6 +38,7 @@ function ScaleD( ) { pivot = +pivot; let [min, max] = domain; + if (descending(min, max) < 0) ([min, max] = [max, min]), (reverse = !reverse); min = Math.min(min, pivot); max = Math.max(max, pivot); diff --git a/test/scales/scales-test.js b/test/scales/scales-test.js index 8f2f0aaa3d..49dd609789 100644 --- a/test/scales/scales-test.js +++ b/test/scales/scales-test.js @@ -361,6 +361,37 @@ it("plot(…).scale(name).unknown reflects the given unknown option for a diverg }); }); +it("plot(…).scale(name) handles a diverging scale with a descending domain", async () => { + const plot = Plot.plot({ + color: {type: "diverging", domain: [100, -10]} + }); + const {interpolate, ...color} = plot.scale("color"); + scaleEqual(color, { + type: "diverging", + symmetric: false, + domain: [-100, 100], + pivot: 0, + clamp: false + }); + for (const t of d3.ticks(0, 1, 100)) { + assert.strictEqual(interpolate(t), d3.interpolateRdBu(1 - t)); + } +}); + +it("plot(…).scale(name) handles a reversed diverging scale with a descending domain", async () => { + const plot = Plot.plot({ + color: {type: "diverging", domain: [100, -10], reverse: true} + }); + scaleEqual(plot.scale("color"), { + type: "diverging", + symmetric: false, + domain: [-100, 100], + pivot: 0, + clamp: false, + interpolate: d3.interpolateRdBu + }); +}); + it("plot(…).scale(name) promotes the given zero option to the domain", async () => { const penguins = await d3.csv("data/penguins.csv", d3.autoType); const plot = Plot.dotX(penguins, {x: "body_mass_g"}).plot({x: {zero: true}});