问题
I have many charts being generated dynamically. For some charts, the dates are near each other, so, axis labels are getting repeated
Example:

Date format used:
d3.time.format("%d-%b-%y")
Is there an in-built way to avoid duplication of labels? Or is there a good generic procedure which can avoid such duplication? Note that my charts have zooming feature also and the incoming data is dynamic, so I can't put in hardcoded values of "ticks" or "tickValues". Generating ticks or tickValues dynamically, could be the way to go.
回答1:
Thank you @Lars Kotthoff for helping out. This is the basic solution:
var ticks = scale.ticks(userSpecifiedTicks);
var nonDuplicateTickValues = [];
var tickAlreadyExists = function(tickValIn)
{
for(var i=0;i<nonDuplicateTickValues.length;i++)
{
var t = nonDuplicateTickValues[i];
var formattedTickValIn = formatter(tickValIn);
var formattedTickVal = formatter(t);
if(formattedTickValIn == formattedTickVal)
{return true;}
}
return false;
};
var removeDuplicateTicks = function()
{
for(var i=0;i<ticks.length;i++)
{
var tickVal = ticks[i];
if(!tickAlreadyExists(tickVal))
{
nonDuplicateTickValues.push(tickVal);
}
}
};
scale.tickValues(nonDuplicateTickValues);
Here, formatter could be any function like:
var formatter = function(d){
var format = d3.time.format("%d-%b-%y");
return format(d);
}
回答2:
You can also use these methods to get distinct values from an array.
d3.set().values()
Input: _.map(d3.set([1,2,3,3,4,5,5]).values(), function(d) { return +d; });
Output: [1, 2, 3, 4, 5]
Without _.map(array, function)
you would get an array of strings as output, so modify as need be.
onlyUnique(value, index, self) { return self.indexOf(value) === index; }
Input: [1,2,3,3,4,5,5].filter(onlyUnique);
Output: [1, 2, 3, 4, 5]
来源:https://stackoverflow.com/questions/26772259/avoid-duplicate-dates-in-d3js-axes