Skip to content

Commit ddfa33e

Browse files
committed
fix tickFormat on a collapsed domain (start == end)
closes #286 closes observablehq/plot#2076
1 parent d6904a4 commit ddfa33e

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/tickFormat.js

+10-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import {tickStep} from "d3-array";
22
import {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from "d3-format";
33

4-
export default function tickFormat(start, stop, count, specifier) {
4+
export default function tickFormat(start, stop, count, specifierIn) {
55
var step = tickStep(start, stop, count),
66
precision;
7-
specifier = formatSpecifier(specifier == null ? ",f" : specifier);
7+
const specifier = formatSpecifier(specifierIn == null ? ",f" : specifierIn);
88
switch (specifier.type) {
99
case "s": {
1010
var value = Math.max(Math.abs(start), Math.abs(stop));
@@ -21,7 +21,14 @@ export default function tickFormat(start, stop, count, specifier) {
2121
}
2222
case "f":
2323
case "%": {
24-
if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
24+
if (specifier.precision == null) {
25+
if (step === 0) {
26+
if (specifierIn == null) specifier.trim = true;
27+
}
28+
else if (!isNaN(precision = precisionFixed(step))) {
29+
specifier.precision = precision - (specifier.type === "%") * 2;
30+
}
31+
}
2532
break;
2633
}
2734
}

test/tickFormat-test.js

+16
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,20 @@ it("tickFormat(start, stop, count) uses the default precision when the domain is
4040
const f = tickFormat(0, NaN, 10);
4141
assert.strictEqual(f + "", " >-,f");
4242
assert.strictEqual(f(0.12), "0.120000");
43+
44+
const f2 = tickFormat(0.12, NaN, 10);
45+
assert.strictEqual(f2 + "", " >-,f");
46+
assert.strictEqual(f2(0.12), "0.120000");
47+
});
48+
49+
it("tickFormat(start, stop, count) uses the default precision with trimming when the domain is collapsed", () => {
50+
const f = tickFormat(5.5, 5.5, 10);
51+
assert.strictEqual(f + "", " >-,~f");
52+
assert.strictEqual(f(0), "0");
53+
assert.strictEqual(f(5.5), "5.5");
54+
assert.strictEqual(f(Math.PI), "3.141593");
55+
assert.strictEqual(f(-Math.PI), "−3.141593");
56+
assert.strictEqual(f(Math.PI * 1e7), "31,415,926.535898");
57+
assert.strictEqual(f(-Math.PI * 1e7), "−31,415,926.535898");
4358
});
59+

0 commit comments

Comments
 (0)