Adding string tags to each value of jQuery Sparklines plugin
-
06-06-2021 - |
Question
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}}">●</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
OTHER TIPS
I also use bootstrap, I ran into this issue where I couldn't see the tooltip:
Globally setting box-sizing to border-box causes tooltip to be displayed incorrectly. This can be fixed by the following css after bootstrap. This may become an issue as box-sizing is more frequently used.
.jqstooltip { box-sizing: content-box;}
Here's the link. https://github.com/gwatts/jquery.sparkline/issues/89
Here is a working example of a pie charts with custom labels
http://jsfiddle.net/gwatts/ak4JW/
// jsfiddle configured to load jQuery Sparkline 2.1
// http://omnipotent.net/jquery.sparkline/
// Values to render
var values = [1, 2, 3];
// Draw a sparkline for the #sparkline element
$('#sparkline').sparkline(values, {
type: "pie",
// Map the offset in the list of values to a name to use in the tooltip
tooltipFormat: '{{offset:offset}} ({{percent.1}}%)',
tooltipValueLookups: {
'offset': {
0: 'First',
1: 'Second',
2: 'Third'
}
},
});