Skip to content

Commit

Permalink
an heuristic to prevent tick occlusion
Browse files Browse the repository at this point in the history
Related: #72
  • Loading branch information
Fil committed Dec 23, 2020
1 parent 5385b8d commit a1a5330
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/marks/axis.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {max} from "d3-array";
import {axisTop, axisBottom, axisRight, axisLeft} from "d3-axis";
import {interpolateRound} from "d3-interpolate";
import {create} from "d3-selection";
Expand Down Expand Up @@ -53,6 +54,7 @@ export class AxisX {
.attr("font-size", null)
.attr("font-family", null)
.call(g => g.select(".domain").remove())
.call(tickOcclusion(width - marginLeft - marginRight, true))
.call(!grid ? () => {} : g => g.selectAll(".tick line").clone(true)
.attr("stroke-opacity", 0.1)
.attr("y2", offsetSign * (marginBottom + marginTop - height)))
Expand Down Expand Up @@ -123,6 +125,7 @@ export class AxisY {
.attr("font-size", null)
.attr("font-family", null)
.call(g => g.select(".domain").remove())
.call(tickOcclusion(height - marginTop - marginBottom, false))
.call(!grid ? () => {} : g => g.selectAll(".tick line").clone(true)
.attr("stroke-opacity", 0.1)
.attr("x2", offsetSign * (marginLeft + marginRight - width)))
Expand All @@ -149,3 +152,16 @@ function round(scale) {
? scale.copy().interpolate(interpolateRound)
: scale;
}

function tickOcclusion(space, horizontal) {
return g => {
const tickLabels = g.selectAll(".tick text");
const n = tickLabels.size();
const M = (.5 + (horizontal ? max(tickLabels, d => d.textContent.length) : 1)) * 6.5;
const m = Math.ceil(n * M / space);
if (m > 1) {
tickLabels.filter((d,i) => i % m).remove();
g.selectAll(".tick line").filter((d,i) => i % m).remove();
}
};
}

0 comments on commit a1a5330

Please sign in to comment.