Search code examples
javascriptd3.jsnvd3.js

Custom tooltip in lineChart of nvd3.js


How to create a custom tooltip in lineChart of nvd3.js?, i want to add a "total" value in the tooltip something like this

enter image description here

I've tried to call the chart.tooltip.contentGenerator, to create a custom tooltip, but the data is empty

chart.tooltip.contentGenerator(function(data) {
    console.log(data) //empty
});

i'am using nvd3 version 1.8.5 and d3 version 3.5.9 only, here's my fiddle: sample


Solution

  • Please try using chart.interactiveLayer.tooltip.contentGenerator. Testing your code with this line, I was able to watch values inside data variable, as you can see below:

    attached capture.

    From here you could construct or edit your custom tooltip as you wish. Let me know if it works for you.

    [EDIT - SUGGESTION TO INCLUDE EVENT BEHAVIOR]

    Looking inside NVD3, I realized that the tooltip's contentGenerator contains all specific code to add events behavior for tooltip. If you take a look at the original tooltip, it uses a class called highlight to mark focused color, but the custom tooltip has not implemented this events and does not highlith focused color.

    I know it's a step back, once you have made you own code for thisd custom tooltip, but seems that the only way to achieve this is to rebuild your code to inlcude event behavior. Maybe starting from the orginal code that NVD3 includes to create tooltip usign contetGenerator will help (thats the way I would take, but it's up to you if you prefer to implement this on your current code).

    If you want to take a look at this code, please find tooltip.js for your NVD3 version or visit this GitHub link

    On this file, if you check at line 83, of just searching for "highlight" on the file, you can see the way event enter() is implemented for all tr elements inside table body, adding the classname highlight.

    var trowEnter = tbodyEnter.selectAll("tr")
        .data(function(p) { return p.series})
        .enter()
        .append("tr")
        .classed("highlight", function(p) { return p.highlight});
    

    My suggestion is to take all this code (I mean all inside contentGenerator function) for your custom contentGenerator, so you can asure that all HTML code is generated true to the original, even with associated behavior, and then override it to include the customization you have made for the title.

    Please, try this and let me know if you can manage to solve the problem.