software_writer
software_writer

Reputation: 4468

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.

Upvotes: 0

Views: 1457

Answers (2)

Taran J
Taran J

Reputation: 805

should work like this below, but you'll need to map your 'data' accordingly.

var data = [40,50,60,70,80]
var days = ["Mon","Tue","Wed","Thu","Fri"]

var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickFormat(function (d,i) {
    return days[i];
});

Upvotes: 2

software_writer
software_writer

Reputation: 4468

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;
    }
});

Upvotes: 1

Related Questions