Search code examples
javascriptjquerysparklines

Adding string tags to each value of jQuery Sparklines plugin


I'm implementing jQuery Sparklines plugin for a web app I'm developing. I want to add tags to the pie chart values so when you hover over that specific chart you will se "Automotive (25%)" instead of the default int value "1 (25%)".

Any ideas on how this could be done?

Here is the code I have:

    $(function(){
        var myvalues = [10,8,5,7,4,4,1];
        $('#sparkline').sparkline(myvalues, {
            type: 'pie',
            width: '200px',
            height: '200px',
            sliceColors: ['#5d3092', '#4dc9ec', '#9de49d', '#9074b1', '#66aa00', '#dd4477', '#0099c6', '#990099'],
            borderWidth: 7,
            borderColor: '#f5f5f5'
        });
    });

Thanks!


Solution

  • A better alternative to using tooltipPrefix or writing your own formatter is to use tooltipFormat and tooltipValueLookups instead to map the index in your array of values to a name:

        $(function() {
        var myvalues = [10,8,5,7,4,4,1];
        $('#sparkline').sparkline(myvalues, {
            type: 'pie',
            width: '200px',
            height: '200px',
            sliceColors: ['#5d3092', '#4dc9ec', '#9de49d', '#9074b1', '#66aa00', '#dd4477', '#0099c6', '#990099'],
            borderWidth: 7,
            borderColor: '#f5f5f5',
            tooltipFormat: '<span style="color: {{color}}">&#9679;</span> {{offset:names}} ({{percent.1}}%)',
            tooltipValueLookups: {
                names: {
                    0: 'Automotive',
                    1: 'Locomotive',
                    2: 'Unmotivated',
                    3: 'Three',
                    4: 'Four',
                    5: 'Five'
                    // Add more here
                }
            }
        });
    });
    

    Here's a link to the Sparkline docs for the above methods: http://omnipotent.net/jquery.sparkline/#tooltips