2

How to use log scale in nvd3 lineChart y-axis? I'm plotting these series which contain very large numbers:

ydata1 = [13947989924.43, 13944328607.2, 13936012870.52, 13792849748.97, 13756681531.69]
ydata2 = [10031442377.14, 10026457857.22, 10013108551.11, 9995581772.15, 9989728780.19]

enter image description here

And because y-axis doesnt start from 0, ydata1 and ydata2 look very far apart. How to adjust this and use a log scale instead?

DougKruger
  • 4,424
  • 14
  • 41
  • 62

1 Answers1

5

My NVD3 is a little rusty, but I think I can help.

Your series will look far apart with a log scale as well (as you suggest), it is just how NVD3 spaces things, so changing the domain of the axis will help. You can change both the scale type and domain of the y axis as follows:

A log axis is created like so:

chart.yScale( d3.scale.log() );

You can set the base like this:

chart.yScale( d3.scale.log().base(2) );

You can also force the y domain to include a specific range by using (remember that "a log scale must have either an exclusively-positive or exclusively-negative domain; the domain must not include or cross zero." (d3 documentation)):

chart.forceY([1000000000,50000000000]);

Which may help you center your data away from the top and bottom edges. I'm not aware of any NVD3 methods that allow you do this automatically, but you could set these values dynamically based on the maximum/minimum values in your datasets.

The below snippet uses a log scale and a forced domain for the y axis:

var chart;
var data;
  
nv.addGraph(function() {
  chart = nv.models.lineChart()
    .x(function (d) { return d.x; })
    .options({showYAxis: true})
    .forceY([1000000000,50000000000]);

data = [{
   key: 1,
 values: [{x:1, y:13947989924},{x:2,y:13944328607},{x:3,y:13936012870}, {x:4,y:13792849748},{x:5,y:13756681531}]
  },{
    key: 2,
  values: [{x:1, y:10031442377},{x:2,y:10026457857},{x:3,y:10013108551}, {x:4,y:9995581772},{x:5,y:9989728780}]
 }]   

chart.yScale( d3.scale.log() );


d3.select('#chart').append('svg')
  .datum(data)
  .call(chart);

nv.utils.windowResize(chart.update);
  return chart;
});
#chart svg {
  width: 500px;
  height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.css" rel="stylesheet" type="text/css">

<div id="chart"></div>
Andrew Reid
  • 37,021
  • 7
  • 64
  • 83