Skip to content

Commit

Permalink
Make y-axis tick precision dynamic
Browse files Browse the repository at this point in the history
In case of a stacked chart, or when the minimum y-value is
more than 1, we use the 0.1f format which is 1 decimal place.
For when the value is less than 1, we calculate how deep is
the most significant digit of the smallest non-zero y-value,
and set that as the tick precision.
  • Loading branch information
rajadain committed Aug 24, 2017
1 parent fba8507 commit dbdcee8
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/mmw/js/src/core/chart.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ function renderCompareMultibarChart(chartEl, name, label, colors, stacked, yMax,
minBarWidth: 120,
maxBarWidth: 150,
},
yTickFormat = stacked ? '0.1f' : yFormat(),
chart = nv.models.multiBarChart(),
svg = makeSvg(chartEl),
$svg = $(svg);
Expand All @@ -335,6 +336,24 @@ function renderCompareMultibarChart(chartEl, name, label, colors, stacked, yMax,
chart.width(chartEl.offsetWidth);
}

function yFormat() {
var getYs = function(d) { return _.map(d.values, 'y'); },
nonZero = function(x) { return x > 0; },
ys = _(data).map(getYs).flatten().filter(nonZero).value(),
minY = Math.min.apply(null, ys);

if (minY > 1) {
return '0.1f';
}

// Count decimal places to most significant digit
for (var i = 0; minY < 1 && i < 20; i++) {
minY *= 10;
}

return '0.0' + i + 'f';
}

nv.addGraph(function() {
chart.showLegend(false)
.showControls(false)
Expand All @@ -349,6 +368,7 @@ function renderCompareMultibarChart(chartEl, name, label, colors, stacked, yMax,

chart.yAxis
.axisLabel(label)
.tickFormat(d3.format(yTickFormat))
.showMaxMin(false);

chart.tooltip.enabled(true);
Expand Down

0 comments on commit dbdcee8

Please sign in to comment.