Question

I'm using nvd3.js to create a line graph that displays ratings that I have calculated over time. I have more information for each individual data point (rating) and would like to have each data point on the graph link to a unique page with more information about that specific data point.

For example: I would like to be able to hover over the first data point on the graph (x: 1345457533, y: -0.0126262626263) and click on it to go to a specific page (http://www.example.com/info?id=1) that provides more information about that rating or data point. Each data point has a unique id and unique url that I would like to link to.

Here is the code that I am using to generate the graph:

nv.addGraph(function() {
  var chart = nv.models.lineChart();

  chart.xAxis
      .axisLabel('Time')
      .tickFormat(d3.format('r'));

  chart.yAxis
      .axisLabel('Rating')
      .tickFormat(d3.format('.2f'));

  d3.select('#chart svg')
      .datum(data())
      .transition().duration(500)
      .call(chart);

  nv.utils.windowResize(chart.update);

  return chart;
});

function data() {
  var data = [ { x: 1345457533, y: -0.0126262626263 },
               { x: 1345457409, y: 0.0224089635854 },
               { x: 1345457288, y: 0.0270935960591 },
               { x: 1345457168, y: -0.0378151260504 },
               { x: 1345457046, y: -0.115789473684 } ]

  return [
    {
      values: data,
      key: "Sample1",
      color: "#232066"
    }
  ];
}

The HTML:

<div id="chart">
  <svg></svg>
</div>

And here is a working example.

Was it helpful?

Solution

Here is an working solution http://jsfiddle.net/66hAj/7/

$('#chart svg').on('click', function(e){
    var elem = $(e.target),
        currentItem, currentUrl;

    if(elem.parent('.nv-point-paths').length) {
        currentItem = e.target.getAttribute('class').match(/\d+/)[0];
        currentUrl = _data[0].urls[ currentItem ];

        $('#log').text(currentUrl);
        //window.location = currentUrl
    }
})

I've used jQuery to bind a click handler on the canvas and then get the data based on the element clicked on the graph.

currentItem gives you the id of the current item that you clicked on

currentUrl gives the url related to the currently clicked item.

You can see the url change in the div below the chart as you click on each point over the graph.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top