Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions draftlogs/7894_add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Add native log-scale colorscale, with new 'colorscaletype': 'log' attribute [[#7894](https://github.com/plotly/plotly.js/pull/7894)]
11 changes: 8 additions & 3 deletions src/components/colorbar/draw.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ function makeColorBarData(gd) {
opts._traceIndex = trace.index;
opts._propPrefix = (contName ? contName + '.' : '') + 'colorbar.';
opts._meta = trace._meta;
opts.type = cont.colorscaletype || 'linear';
calcOpts();
out.push(opts);
}
Expand All @@ -151,6 +152,7 @@ function makeColorBarData(gd) {
opts._id = 'cb' + k;
opts._propPrefix = k + '.colorbar.';
opts._meta = fullLayout._meta;
opts.type = cont.colorscaletype || 'linear';

cbOpt = {min: 'cmin', max: 'cmax'};
if(colorAxOpts[0] !== 'heatmap') {
Expand Down Expand Up @@ -955,8 +957,11 @@ function mockColorBarAxis(gd, opts, zrange) {
var isVertical = opts.orientation === 'v';

var cbAxisIn = {
type: 'linear',
range: zrange,
type: opts.type || 'linear',
// Colorscale.calc guarantees zrange is strictly positive whenever
// opts.type is still 'log' by the time we get here
range: opts.type === 'log' ?
[Math.log10(zrange[0]), Math.log10(zrange[1])] : zrange,
tickmode: opts.tickmode,
nticks: opts.nticks,
tick0: opts.tick0,
Expand Down Expand Up @@ -993,7 +998,7 @@ function mockColorBarAxis(gd, opts, zrange) {
var letter = isVertical ? 'y' : 'x';

var cbAxisOut = {
type: 'linear',
type: cbAxisIn.type,
_id: letter + opts._id
};

Expand Down
11 changes: 11 additions & 0 deletions src/components/colorscale/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,17 @@ module.exports = function colorScaleAttrs(context, opts) {
].join(' ')
};

attrs.colorscaletype = {
valType: 'enumerated',
values: ['linear', 'log'],
dflt: 'linear',
editType: 'calc',
description: [
'Sets the colorscale type.' + effectDesc,
'If `"log"`, the colorscale and colorbar will be configured for logarithmic data.'
].join(' ')
};

if (!noScale) {
attrs.showscale = {
valType: 'boolean',
Expand Down
42 changes: 40 additions & 2 deletions src/components/colorscale/calc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,24 @@ var isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var extractOpts = require('./helpers').extractOpts;

// mirrors Lib.aggNums's own recursion into nested (eg heatmap z) arrays, but
// masks out non-positive values first - matching how cartesian log axes
// exclude non-positive data from autorange (see findExtremes in
// plots/cartesian/autorange.js)
function maskNonPositive(vals) {
if(Lib.isArrayOrTypedArray(vals[0])) return vals.map(maskNonPositive);

var out = new Array(vals.length);
for(var i = 0; i < vals.length; i++) {
var v = vals[i];
out[i] = (isNumeric(v) && v > 0) ? v : undefined;
}
return out;
}

module.exports = function calc(gd, trace, opts) {
var fullLayout = gd._fullLayout;
var vals = opts.vals;
var rawVals = opts.vals;
var containerStr = opts.containerStr;

var container = containerStr ?
Expand All @@ -20,6 +35,27 @@ module.exports = function calc(gd, trace, opts) {
var max = cOpts.max;
var mid = cOpts.mid;

var scaleType = cOpts.colorscaletype || 'linear';
var isLog = scaleType === 'log';

if(isLog) {
// a log colorbar needs a strictly positive domain: an explicit
// non-positive cmin/cmax can never be logged, and if this trace's
// data is going to be scanned for an auto min/max but has no
// positive values at all, there's nothing to scale from. Either way,
// fall back to a linear colorbar instead of an undefined/negative range.
var fullyPinned = !auto && isNumeric(min) && isNumeric(max);
var hasExplicitNonPositive = (isNumeric(min) && min <= 0) || (isNumeric(max) && max <= 0);
var hasPositiveData = fullyPinned || isNumeric(Lib.aggNums(Math.max, null, maskNonPositive(rawVals)));

if(hasExplicitNonPositive || !hasPositiveData) {
isLog = false;
if(cOpts.colorscaletype) cOpts._sync('colorscaletype', 'linear');
}
}

var vals = isLog ? maskNonPositive(rawVals) : rawVals;

var minVal = function() { return Lib.aggNums(Math.min, null, vals); };
var maxVal = function() { return Lib.aggNums(Math.max, null, vals); };

Expand All @@ -43,7 +79,9 @@ module.exports = function calc(gd, trace, opts) {
}
}

if(auto && mid !== undefined) {
// a symmetric-around-cmid range is a linear-domain concept - skip it for
// log colorbars rather than risk pushing a positive min/max non-positive
if(auto && mid !== undefined && !isLog) {
if(max - mid > mid - min) {
min = mid - (max - mid);
} else if(max - mid < mid - min) {
Expand Down
1 change: 1 addition & 0 deletions src/components/colorscale/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ module.exports = function colorScaleDefaults(parentContIn, parentContOut, layout

coerce(prefix + 'colorscale');
coerce(prefix + 'reversescale');
coerce(prefix + 'colorscaletype');

if(prefix !== 'marker.line.') {
// handles both the trace case where the dflt is listed in attributes and
Expand Down
41 changes: 39 additions & 2 deletions src/components/colorscale/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function hasColorscale(trace, containerStr, colorKey) {
);
}

var constantAttrs = ['showscale', 'autocolorscale', 'colorscale', 'reversescale', 'colorbar'];
var constantAttrs = ['showscale', 'autocolorscale', 'colorscale', 'reversescale', 'colorbar', 'colorscaletype'];
var letterAttrs = ['min', 'max', 'mid', 'auto'];

/**
Expand Down Expand Up @@ -116,6 +116,17 @@ function extractScale(cont) {
var cmin = cOpts.min;
var cmax = cOpts.max;

// Check if a colorscale type is 'log'
// (Colorscale.calc guarantees cmin/cmax are strictly positive whenever
// type is still 'log' by the time we get here - see maskNonPositive)
var type = cOpts.colorscaletype || 'linear';

// Convert domain boundaries to base-10 log if required
if(type === 'log') {
cmin = Math.log10(cmin);
cmax = Math.log10(cmax);
}

var scl = cOpts.reversescale ?
flipScale(cOpts.colorscale) :
cOpts.colorscale;
Expand Down Expand Up @@ -206,7 +217,33 @@ function makeColorScaleFunc(specs, opts) {
}

function makeColorScaleFuncFromTrace(trace, opts) {
return makeColorScaleFunc(extractScale(trace), opts);
var cOpts = extractOpts(trace);
var type = cOpts.colorscaletype || 'linear';
var baseColorFn = makeColorScaleFunc(extractScale(trace), opts);

if(type !== 'log') return baseColorFn;

opts = opts || {};
var noNumericCheck = opts.noNumericCheck;
var returnArray = opts.returnArray;

// Wrap the base generator to dynamically apply log transformations,
// matching the array/string return shape makeColorScaleFunc would have used
var wrappedFunc = function(v) {
if(noNumericCheck || isNumeric(v)) {
// log of zero/negative is undefined - treat as out-of-range
if(v > 0) return baseColorFn(Math.log10(v));
return returnArray ? [0, 0, 0, 0] : 'rgba(0,0,0,0)';
} else if(tinycolor(v).isValid()) {
return v;
}
return Color.defaultLine;
};

// Preserve native domain and range methods for the draw components
wrappedFunc.domain = baseColorFn.domain;
wrappedFunc.range = baseColorFn.range;
return wrappedFunc;
}

module.exports = {
Expand Down
91 changes: 91 additions & 0 deletions test/jasmine/tests/colorbar_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,4 +620,95 @@ describe('Test colorbar:', function() {
.then(done, done.fail);
});
});

describe('log ticks', function() {
var gd;

beforeEach(function() {
gd = createGraphDiv();
});

afterEach(destroyGraphDiv);

it('should generate logarithmic ticks when type is log', function() {
Plotly.newPlot(gd, [{
type: 'heatmap',
z: [[1, 10, 100], [10,100,1000]],
cmin: 1,
cmax: 1000,
colorscaletype: 'log',
colorbar: {
tickmode: 'auto'
}
}]);

// Extract the tick text elements
var tickTexts = [];
d3Select(gd).selectAll('.cbaxis text').each(function(t) {
tickTexts.push(t.text);
});

// The mock axis should have automatically generated exponents for 1, 10, 100, 1000
expect(tickTexts).toContain('1');
expect(tickTexts).toContain('2');
expect(tickTexts).toContain('5');
expect(tickTexts).toContain('10');
expect(tickTexts).toContain('100');
expect(tickTexts).toContain('1000');

// // Verify a linear tick like '500' was NOT generated
expect(tickTexts).not.toContain('500');
});

it('should fall back to a linear colorbar when zmin is explicitly non-positive, instead of a NaN-derived range', function(done) {
Plotly.newPlot(gd, [{
type: 'heatmap',
z: [[-5, 10, 100], [10, 100, 1000]],
zmin: -5,
zmax: 1000,
colorscaletype: 'log',
colorbar: {
tickmode: 'auto'
}
}])
.then(function() {
var ax;
gd._fullLayout._infolayer.selectAll('g.colorbar').each(function(opts) {
ax = opts._axis;
});

// a log colorbar can't represent a non-positive zmin, so the
// whole colorbar (and its mocked axis) falls back to linear
// instead of producing a NaN/folded log range
expect(gd._fullData[0].colorbar.type).toBe('linear');
expect(ax.type).toBe('linear');
expect(ax.range).toEqual([-5, 1000]);
})
.then(done, done.fail);
});

it('should mask out non-positive z values and stay log when autoscaling with mixed-sign data', function(done) {
Plotly.newPlot(gd, [{
type: 'heatmap',
z: [[-5, 2, 100], [10, 100, 1000]],
colorscaletype: 'log',
colorbar: {
tickmode: 'auto'
}
}])
.then(function() {
var ax;
gd._fullLayout._infolayer.selectAll('g.colorbar').each(function(opts) {
ax = opts._axis;
});

expect(gd._fullData[0].colorbar.type).toBe('log');
expect(ax.type).toBe('log');
// -5 is masked out of autorange; smallest positive value (2) is zmin
expect(ax.range[0]).toBeCloseTo(Math.log10(2), 5);
expect(ax.range[1]).toBeCloseTo(Math.log10(1000), 5);
})
.then(done, done.fail);
});
});
});
Loading
Loading