Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 linechart string domain x-axis

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

like image 261
Vincent Hogendoorn Avatar asked Mar 22 '13 09:03

Vincent Hogendoorn


2 Answers

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.

like image 54
Lars Kotthoff Avatar answered Sep 22 '22 03:09

Lars Kotthoff


Use

var x = d3.scale.ordinal().rangePoints([0, width]);

Here is Fiddle Link http://jsfiddle.net/sk2Cf/

like image 24
gunjan Avatar answered Sep 24 '22 03:09

gunjan