Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line chart using ordinal x-axis with d3.js and nvd3.js

I am trying to make a line chart from a dataset while keeping X-axis categorical. For the observer it will look like a line chart with equidistant spacing between observations' X coordinates:

( 1 ------ 5 ------ 30 ------ 600)

For now I am getting something like this:

(1-5-----30-------------------600)

This is my dataset:

var ds1 =  [
  {
    key: 'VAR-1',
    color: '#FF7F0E',
    values: [
   { "x" : "600", "y" : 0.07706} 
 , { "x" : "30", "y" : 0.00553} 
 , { "x" : "5", "y" : 0.00919} 
 , { "x" : "1", "y" : 0.00969} 
    ]
  }
];

I tried to create the ordinal axis and set it in the line chart object:

var chart =nv.models.lineChart()
             .margin({top: 10, bottom: 40, left: 60, right: 30});   
var x = d3.scale.ordinal().domain(["1","5", "30", "600"]);
chart.xAxis.scale(x);

chart.yAxis
    .tickFormat(d3.format(',.3f'));

chart.forceY([0]);

d3.select('#exampleOne')
    .datum(ds1)
    .transition().duration(500)
    .call(chart);

Nothing seems to be changing on the plot however.

I was wondering, could the ordinal axis be enabled at all in the NVD3 line chart implementation or this line chart was written for numerical data only?

PS: I am new to d3.js, so I might be doing something wrong here.

like image 207
user1946927 Avatar asked Jan 03 '13 22:01

user1946927


1 Answers

Try setting rangeBounds([0, chartWidth]) for the scale. i.e

d3.scale.ordinal().domain(["1","5", "30", "600"]).rangeBounds([0, width]);

Correction : I thought your scales needed to be changed, but you actually want the line plotted to be have the values plotted equidistant. To do this you may want to modify the dataset you are sending to the lineGraph to something like.

var ds1 =  [ {
key: 'VAR-1',
color: '#FF7F0E',
values: [
{ "x" : "4", "y" : 0.07706} 
, { "x" : "3", "y" : 0.00553} 
, { "x" : "2", "y" : 0.00919} 
, { "x" : "1", "y" : 0.00969} 
]}
];

That way while the values shown in the x-axis will be ordinal (i.e 1, 5, 30, 600), the values plotted for the line will be on a linear scale.

like image 108
baradas Avatar answered Nov 15 '22 01:11

baradas