Search code examples
d3.jsdata-visualizationgraph-visualization

Linear scale with labels in D3


Is it possible in D3 to have a linear scale but use (ordinal-style) labels?

I want to display month names under X-axis. I used ordinal scale at first and it worked fine; but turns out D3 zoom doesn't work with ordinal scale.

So I want to have the linear scale(0-11 as month numbers) but somehow get month names when we render the axis. Is that possible? Any suggestions/workarounds are appreciated.


Solution

  • I achieved this using Axis.tickFormat

    For example,

    var y = d3.scale.linear()
    .range([height, 0]);
    
    var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5)
    .tickFormat(function (d) {
        switch(d) {
            case 40: return "Monday"; break;
            case 50: return "Tuesday"; break;
            case 60: return "Wednesday"; break;
            case 70: return "Thursday"; break;
            case 80: return "Friday"; break;
        }
    });