Skip to content

Commit

Permalink
fix: color by rank when rank has ties #29
Browse files Browse the repository at this point in the history
  • Loading branch information
mxposed committed Feb 3, 2025
1 parent 23cb639 commit 2365612
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/columns.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** @module */

import * as d3 from 'd3';
import _ from 'lodash';

import { rowToColData } from './input_util';

Expand Down Expand Up @@ -147,7 +148,10 @@ export class Column {
this.scale = d3.scaleLinear().domain(extent);
if (this.colorByRank) {
this.rankedData = d3.rank(this.data);
this.colorScale = d3.scaleLinear().domain([0, this.data.length - 1]);
const uniqueRanks = _.uniq(this.rankedData);
const rankedRanks = d3.rank(uniqueRanks);
this.normalizedRanks = _.zipObject(uniqueRanks, rankedRanks);
this.colorScale = d3.scaleLinear().domain([0, uniqueRanks.length - 1]);
}
}

Expand All @@ -164,7 +168,9 @@ export class Column {
return item[this.id_color];
}
if (this.colorByRank) {
return this.rankedData[itemPos];
const rank = this.rankedData[itemPos];
const normalizedRank = this.normalizedRanks[rank];
return normalizedRank;
}
return item[this.id];
}
Expand Down
10 changes: 9 additions & 1 deletion tests/columns.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,16 @@ describe('column class', function() {
const info = {id: 'a', colorByRank: true};
const data = [5, 2, 1];
const column = new Column(info, data);
column.maybeCalculateStats(true);
assert.equal(column.getColorValue({'a': 5}, 0), 2);
assert.equal(column.getColorValue({'a': 2}, 1), 1);
assert.equal(column.getColorValue({'a': 1}, 2), 0);
});
it('should return colorValue with colorByRank with ties', function() {
const info = {id: 'a', colorByRank: true};
const data = [1, 1, 2];
const column = new Column(info, data);
assert.equal(column.getColorValue({'a': 1}, 0), 0);
assert.equal(column.getColorValue({'a': 2}, 2), 1);
});
it('should return colorValue with id_color option', function() {
const info = {id: 'a', id_color: 'b'};
Expand Down

0 comments on commit 2365612

Please sign in to comment.