Avoid duplicate dates in d3js axes

a 夏天 提交于 2019-12-11 09:36:21

问题


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.

  1. 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.

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!