NVD3 accessing a chart object
Asked Answered
T

2

0

In previous version's of nvd3 you can do the following to access the chart/graph object.

chart = nv.graphs[0];

However in more recent versions this seems to have been removed:

nv.graphs -> undefined
nv.graphs[0] -> TypeError: nv.graphs is undefined

Is there an alternative way to access the chart elements as such?

chart = nv.graphs[0];
a = chart.brushExtent();

Here's a simple jsfiddle where you can see this in action as well,

http://jsfiddle.net/0m8jzetx/3/

Here is the git issue where they remove it.

Tack answered 7/10, 2015 at 17:44 Comment(0)
I
1

I don't have a real answer, but have found something that may help accessing brushextents:
Rather than declaring chart as a global var, you can declare 2 global var for your extents, and update them when brush is updated, like so:

chart.dispatch.on('brush.update', function(b) {
  curve_focus_min = b.extent[0];
  curve_focus_max = b.extent[1];
});
Inhuman answered 12/11, 2015 at 11:18 Comment(0)
F
1

The short answer seems to be that you should capture the chart when it's created, so for example:

var chart;

nv.addGraph(function () {
  chart = nv.models.lineChart();
  //...
  return chart;
});

// "at some point" - by the time an `on click' is called,
// `chart` will be usable.

If you need more rigour with the validity of chart being defined, the nv.addGraph() function has an optional second argument that is a callback:

It will be called with the generated chart as its only argument. The callback is called immediately following graph generation, and before generation of any other graphs that may be scheduled for generation.

As described on the NVD3 wiki.

So this can be used to capture a reference or use it immediately:

const charts = [];

function capture(chart) {
  charts.push(chart);
}

nv.addGraph(function () {
  const chart = nv.models.lineChart();
  //...
  return chart;
},
capture);
Forbis answered 17/4 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.