I'm relatively new to D3, and I can't figure out why something isn't working. I want to draw a line-chart with d3, and this works fine, but I have problems with the axes.
With the following code it goes wrong somewhere and I don't see how to solve...
var x = d3.scale.linear()
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
x.domain(d3.extent(data, function(d) { return d.age; }));
If d.age
is an integer (like 1;2;3
etc.), it works well. But I want strings on the x-axis. Like ("netherlands", "England", "Belgium")
.
So if d.age
is an integer it draws the graph OK, if d.age is a string it doesn't draw anything.
I have also tried instead of linear to use ordinal, but this gave an incorrect chart. (Weird looking lines...).
If you want to use categorical values on an axis, you need a categorical (ordinal) scale. Have a look at the documentation. Your code would look something like
var x = d3.scale.ordinal().rangeRoundBands([0, width]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
x.domain(data.map(function(d) { return d.country; }));
Note that this uses map
to extract the string values -- this may or may not be implemented in your particular browser, see here for more details.