theHaggis theHaggis - 2 months ago 12
Javascript Question

NVD3.js yAxis and tooltip different percision

I'm using NVD3.js to display a multi-line chart.

I would like the yAxis to display to 2 decimal numbers

edited answer

var chart;

nv.addGraph(function () {
chart = nv.models.lineChart()
margin: { left: 140, bottom: 50 },
x: function (d, i) {
return i;
showXAxis: true,
showYAxis: true,
transitionDuration: 250,
tooltips: true,
tooltipContent: function (key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + e.point.y + ' at ' + x + '</p>'

// chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
.tickFormat(function(d) { return pivotedData[0].values[d].x; });

.axisLabel('Model Spread').tickFormat(d3.format(',.2f'));'#chart1 svg')

//TODO: Figure out a good way to do this automatically

chart.dispatch.on('stateChange', function (e) { nv.log('New State:', JSON.stringify(e)); });

return chart;

But in the tool tip on the lines i would like to display to 12 decimals places.

Is this possible?


You can set the function that is called to format the contents of a tooltip through .tooltipContent of the chart object. The default function is defined as follows.

tooltip = function(key, x, y, e, graph) {
    return '<h3>' + key + '</h3>' +
           '<p>' +  y + ' at ' + x + '</p>'

You can format the value of y in there to your liking. Note that y is defined as

yAxis.tickFormat()(lines.y()(e.point, e.pointIndex))

This means that the tick formatting for the axis will affect it, so in order to achieve a higher precision there, you need to get the value directly -- lines can be accessed through chart.lines.