Tooltips on your charts
- Example
- Introduction to tooltips
- What can they hold?
- How can I specify them?
- What can I specify?
- Can I show charts in tooltips?
- Can I customise the appearance of tooltips?
- Customising the default appearance of tooltips in JavaScript
- Using formatting macros in your CSS values
- What tooltip effects are available?
- Can I override the tooltip function?
- Formatted tooltips
Example
Here's an example of a Bar chart
that's using
templated tooltips so that you just have to specify a
single string
to the tooltips
property and
then RGraph adds in the correct values. The source code to the chart
is shown underneath.
<script>
new RGraph.Bar({
id: 'cvs',
data: [8,4,6,3,5,1,2],
options: {
xaxisLabels: ['Alice','John','Alex','Rich','Jan','Lucy','Fred'],
textSize: 16,
textBold: true,
tooltips: '%{property:xaxisLabels[%{dataset}]}: %{value}kg',
tooltipsCss: {
fontSize: '20pt'
},
marginInner: 20,
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxis: false,
yaxis: false
}
}).draw();
</script>
Introduction to tooltips
Tooltips are a very effective and straightforward way to extend your charts and add more information to them, without overloading the user.
What can they hold?
At the base level, tooltips are div
tags, so they can hold a
multitude of
html
- images, videos etc. See below
for information about showing charts in tooltips.
How can I specify them?
You can specify them by including the tooltips and dynamic
library files
- RGraph.common.tooltips.js
and
RGraph.common.dynamic.js
- and then
using the tooltips
property. For example:
-
Include the RGraph libraries.
<script src="RGraph.common.core.js"></script> <script src="RGraph.common.dynamic.js"></script> <script src="RGraph.common.tooltips.js"></script> <script src="RGraph.line.js"></script>
-
Define your chart and set the tooltips property.
<script> new RGraph.Line({ id: 'cvs', data: [64,34,26,35,51,24], options: { marginInner: 10, linewidth: 2, shadowOffsetx: 0, shadowOffsety: 0, shadowColor: 'green', shadowBlur: 25, color: ['green'], tickmarksStyle: 'endcircle', xaxisLabels: ['John', 'Fred', 'Jane', 'Lou', 'Pete', 'Kev'], tooltips: ['<b>Winner!</b><br />John','Fred','Jane','Lou','Pete','Kev'] } }).draw(); </script>
What can I specify?
The tooltips that you specify are usually strings (which can
contain html
tags). They can, however, also be functions that are
called when they're about
to be displayed. The function should return the text that's
to be used as the tooltip. You have the option to either specify
one function per data point or just one function for all
of the tooltips. You can mix functions and strings if you wish.
These functions are passed the numerical, zero-indexed tooltip
index and the return value is used as the tooltip
text. So to summarise:
New in version 5.22 is the ability to also just specify a single string of text that has various macros (bits of text) that are then substituted for the relevant value. An example of this is:
tooltips: 'The value was: %{value_formatted}'
-
A single string (formatted tooltips)
This is probably the most useful option and will mean that you have to write less code. If you use a single string in conjunction with the formatted tooltips feature it can significantly cut down how muchjavascript
code that you have to write and "centralises" the tooltiphtml
that gets shown to the user. For example, your chart code could be:<script> new RGraph.Bar({ id: 'cvs_tooltip_templates', data: [[5,3],[9,1],[6,6],[5,9],[5,5],[4,3],[5,9]], options: { // A custom property that can be used in the tooltips myNames: ['Dave','Richard'], colors: ['Gradient(#faa:red)','Gradient(#aaf:blue)'], xaxisLabels: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], xaxis: false, yaxis: false, backgroundGridBorder: false, backgroundGridVlines: false, tooltips: '<strong>Score for %{property:myNames[%{index}]} on %{property:xaxisLabels[%{dataset}]}: %{value}kg</strong>' } }).wave(); </script>
There are demos in the download archive named
*-tooltip-formatted.html
which demonstrate this feature. -
An array of strings
The string is used as the tooltip. Eg:obj.set({ tooltips: ['John', 'Fred', 'Lou', ...] });
-
An array of function objects
Each function is called and should return the text to be used. Eg:obj.set({ tooltips: [getJohnTooltip, getFredTooltip, getLouTooltip, ...] });
-
A single function object
This function is called whenever a tooltip is about to be displayed and it's passed the numerical, zero-indexed tooltip index of the point on the chart. The function should return the text to be used as the tooltip. Note that the function you specify is called before the tooltipdiv
has been created, so you cannot access it. If you wish to customise the appearance of the tooltip, you can use either the tooltip CSS class or a call tosetTimeout
. Eg:obj.set({ tooltips: getTooltip, ... });
-
An array of
This will make working with large tooltips easier. You specify the ID of adiv
idsdiv
whoseinnerHTML
is then used as the tooltip. Only the contents of thediv
are used, not thediv
itself, so you can hide thediv
by setting itsdisplay
css
value tonone
. For example:obj.set({ tooltips: ['id:myDiv', ...] })
Can I show charts in tooltips?
You can, and with the custom event support that RGraph has, it's reasonably easy. Simply attach your function that
creates the chart to the tooltip
event. This allows the tooltip html
to be created and added to the page
so that the code that creates the chart can run. The sequence is:
- Specify the
html
for the tooltip as normal (including thecanvas
tag). - Use the
tooltip
RGraph event so that a function is called when a tooltip is shown. - This function should subsequently create the chart.
The tooltip div
is to be found in the RGraph registry - RGraph.Registry.get('tooltip')
. And if you want it the
numerical zero indexed count of the tooltip is to be found in the __index__
property:
RGraph.Registry.get('tooltip').__index__
<script src="RGraph.common.core.js" ></script>
<script src="RGraph.common.tooltips.js" ></script>
<script src="RGraph.common.dynamic.js" ></script>
<script src="RGraph.bar.js" ></script>
<script src="RGraph.line.js" ></script>
<style>
.RGraph_tooltip {
background-color: white ! important;
}
</style>
<canvas id="cvs" width="600" height="250">[No canvas support]</canvas>
<script>
labels = ['Gary','Pete','Lou','Ned','Kev','Fred'];
bar = new RGraph.Bar({
id: 'cvs',
data: [4.5,28,13,26,35,36],
options: {
tooltips: '%{property:xaxisLabels[%{dataset}]}s stats <br/> <canvas id="__tooltip_canvas__" width="400" height="150">[No canvas support]</canvas>',
tooltipsPointer: false,
marginInner: 10,
tickmarksStyle: 'endcircle',
colors: ['blue'],
yaxisScaleMax: 100,
xaxisLabels: labels,
xaxis: false,
yaxis: false
}
}).draw();
line.ontooltip = CreateTooltipGraph;
//
// This is the function that is called by the tooltip
event to
// create the tooltip charts
//
// @param obj object The chart object
//
function CreateTooltipGraph(obj)
{
// This data could be dynamic
var line = new RGraph.Line({
id: '__tooltip_canvas__',
data: [5,8,7,6,9,5,4,6,3,5,4,4],
options: {
xaxisLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
marginInner: 5,
tickmarksStyle: 'endcircle'
}
}).draw();
}
</script>
Can I customise the appearance of tooltips?
Yes. You can either use the default css
class RGraph_tooltip
, or you can specify a specific css
class that a
charts tooltips should use with the property tooltipsCssClass
.
Two charts on the same page can have significantly
different-looking tooltips by using this method.
For example:
obj.set({ tooltipsCssClass: 'bar_chart_tooltips' });
<style> .bar_chart_tooltips { background-color: white ! important; border: 2px solid black ! important; padding: 3px; } </style>
There's also the pointer which you may wish to customise
(eg the color) and you can do that too with css
by using the following css
selector. This first example can
be used when you have one or more
<div>
tags in your tooltips in order
to specifically select the tooltip pointer that RGraph
adds:
<style> div.RGraph_tooltip div[id^=RGraph_tooltipsPointer] { background-color: red !important; } </style>
Or if you don't use <div>
tags in
your tooltips you don't need to use the regex
selector (but there's nothing stopping you
using it if you want to):
<style> div.RGraph_tooltip div { background-color: red !important; } </style>
Customising the appearance of tooltips in your charts configuration
New in version 5.22 was the addition of the tooltipsCss
property. This allows you
to specify the style of a chart's tooltips in the charts configuration code. These styles will
only be applied to that chart's tooltips (instead of the tooltips for every chart on the page).
For example (remember to use the javascript
versions of the css
property names):
tooltipsCss: { backgroundColor: 'black', color:'white', fontSize: '18pt' }
Customising the default appearance of tooltips in JavaScript
If you want to set the default style that's used for tooltips you can do so
in your javascript
code. All of the styles are applied to the tooltip by copying them
from the RGraph.tooltips.style
object. Remember to use the javascript
names of the css
properties (capitals instead of hyphens). You only need
to set this once (eg after your call to draw
) and then these defaults are used for every tooltip after
that.
RGraph.tooltips.style.fontFamily = 'Arial'; RGraph.tooltips.style.fontSize = '10pt'; RGraph.tooltips.style.fontWeight = 'normal'; RGraph.tooltips.style.textAlign = 'center'; RGraph.tooltips.style.backgroundColor = 'rgb(255,255,239)'; RGraph.tooltips.style.color = 'black'; RGraph.tooltips.style.borderRadius = '5px'; RGraph.tooltips.style.boxShadow = 'rgba(96,96,96,0.5) 0 0 5px';
These defaults are used for ALL tooltips - if you want to customise just one charts tooltips (and you have multiple charts with tooltips on the page) then use the CSS class method mentioned above.
Using formatting macros in your CSS values
What if you want some of your tooltips to have one color for their border but other tooltips
to use a different color? This isn't catered for by just css
alone, so RGraphs formatting options can do this for you.
This means that when you use the css
options that are available to you (ie the tooltipsCss
configuration
option and when you use javascript
to customise tooltips) you can use formatting identifiers in the css
values like
this:
new RGraph.Bar({ id: 'cvs', data: [[4,2,2],[4,8,6],[3,5,8],[4,8,5],[4,1,2],[1,9,5],[7,8,6]], options: { tooltips: 'Result of the competition:<br /><span style="font-size: 26pt">%{property:names[%{dataset}]}', borderColors: ['red','#0f0','blue'], colors: ['green','pink','orange'], tooltipsCss: { border: '3px solid %{property:borderColors[%{index}]}' } } }).draw(); RGraph.tooltips.style.backgroundColor = '%{property:colors[%{index}]}';
So when you use the tooltipsCss
property you can put formatting macros in the
values and also when you use the RGraph.tooltips.style
or
RGraph.tooltips.css
objects you can use macros too.
Obviously, some of the macros (the %{key}
macro, for example) simply have no use when used
inside css
values - so there's no point trying to use them here.
For an example of this in action, you can look at the
source code of the line-tooltips-dataset.html
demo which is in the download (in the demos/
folder).
Note
Formatting macros can also be used in svg
chart tooltips as well as canvas
.
What tooltip effects are available?
The default effect is slide
, which causes
the tooltip to slide to the new position from the
previous tooltips' position or if it's the first tooltip
that's shown on the page then it will slide from from
the top left corner of the page.
Other available tooltip effects are
fade
and also none
- both
of which are self explanatory.
Can I override the tooltip function?
You can, by stipulating tooltipsOverride
.
This should be a function that handles everything
to do with showing
the tooltip. Highlighting the chart is still done for
you - the override function is only concerned with showing
the tooltip. The override function is passed these
arguments:
obj
- The RGraph chart object.text
- The tooltip text (id:xxx
strings are NOT expanded)x
- The X coordinate in relation to the entire pagey
- The Y coordinate in relation to the entire pageindex
- The numerical index of the tooltip in the original tooltip array
Note: Although id:xxx
strings are not expanded for you, you can easily do this yourself by using the
RGraph.getTooltipText('id:xxx')
function.
<script> function tooltip_override (obj, text, x, y, idx) { alert('In tooltip override function...'); } myObj.set({ tooltipsOverride: tooltip_override }); </script>
Formatted tooltips
Formatted tooltips are a new addition to RGraph version 5.22 and make building dynamic tooltips much easier.
Instead of giving an array of tooltips like this:
tooltips: ['Richard: 48%','Neil: 95%','Jill: 88%','Milly: 69%','Lucy: 76%','John: 90%']
You can give a single tooltip (a string) that has certain macros in it which get replaced with the relevant value by RGraph just before the tooltip is displayed. So less coding for you and the code that you do have to write looks prettier! The example above would be transformed into this:
myNames: ['Richard','Neil','Jill','Milly','Lucy','John'], // A custom property myScores: [48,95,38,69,76,90], // A custom property tooltips: '%{property:myNames[%{dataset}]}: %{property:myScores[%{dataset}]}%'
You may be thinking: "But that's actually more code!" And yes, that's true in this example, but there's more structure, less "hard-coding" of values and it's easier to write and maintain.
In fact, your tooltips could be as simple as this (which is replaced with the label and the value of the data-point formatted with a decimal point and thousand separators of your choosing along with units):
tooltips: '${property:xaxisLabels[%{dataset}]}: %{value_formatted}'
Example code that uses tooltip macros
Example code for formatted tooltips is shown above.
And there's
a demo page that has been converted to use the macros
here.
What macros are available for me to use?
The macros that are available for you to use are as follows. These macros are expanded to the relevant values when they're shown:
-
%{index}
This gets replaced with the index of the relevant bar/point/segment etc. You may need to experiment with this and the next macro to get the one that you want - they differ slightly when going from regularBar charts
(using theBar chart
as an example) to grouped/stacked charts. -
%{dataset}
This gets replaced with the dataset of the relevant bar/point/segment. You may need to experiment with this and the previous macro to get the one that you want - they differ slightly when going from regularBar charts
(using theBar chart
as an example) to grouped/stacked charts. -
%{dataset2}
This macro is unique to theBipolar chart
. Say for example, you have 7 bars on each side of the chart, the%{dataset}
macro would have values ranging from 0 - 13. This macro however would have values from 0 - 6 regardless of which side you clicked on. So it could be useful if you were attempting to get hold of the relevant label (since there would only be 7 labels). -
%{seq}
%{sequential_index}
This macro gets replaced with the sequential index of the bar/point/segment. So for example, in a stackedBar chart
with 7 bars each having 3 segments this would go from 0 up to 20. -
%{property:title}
This macro fetches single value properties like thetitle
property (ie strings or numbers). -
%{property:xaxisLabels[%{index}]}
With this macro, you can fetch corresponding values from arrays - such as thexaxisLabels
property. As shown here you can combine this macro with the%{index}
or%{dataset}
macros to fetch the relevant value. This macro is used in the example code in conjunction with thexaxisLabels
property and also themyNames
custom property if you want to see an example. -
%{global:foo.bar.myGlobal}
%{global:foo.bar.myGlobal[%{index}]}
%{global:foo.bar.myGlobal[%{dataset}]}
This macro gives you access to global variables - both strings/numbers and also arrays. -
%{value}
%{value2}
(canvasRose chart
and non-stackedsvg
non-equi-angularRose chart
only)
%{value_formatted}
With these macros, you can add the value of the bar/point/segment to your tooltip. The%{value_formatted}
property gives you a formatted value instead of the raw number. For example instead of1575886.2
you could get this:$1,575,886.20c
. The formatting properties are:TheName: tooltipsFormattedThousandDescription:This character is used as the thousand separator.Default: ,Name: tooltipsFormattedDecimalsDescription:This specifies the number of decimals that are shown.Default: 0%{value2}
macro is specific to theRose chart
and provides you access to the second data-point value. -
%{function:getValue(%{index})}
%{function:getValue(%{index}, %{dataset})}
%{function:getValue(%{index}, %{dataset}, %{seq})}
This option allows you to call a function that formats and returns the desired value. When the template macros are parsed by RGraph this is parsed last so you can use other macros in the arguments, as shown, and they end up looking like this:
%{function:getValue(3)}
%{function:getValue(3, 1)}
%{function:getValue(3, 1, 7)}
So those values get passed to the function and you can use them to generate and return the correct value. The return value is then used in the tooltip string. An RGraph Registry variable is available to the function for you to get hold of the chart object and you can get that like this:
var obj = RGraph.Registry.get('tooltip-templates-function-object');
(canvas)
var obj = RGraph.SVG.REG.get('tooltip-templates-function-object');
(SVG) -
%{key}
This macro allows you to easily show a key in your tooltips. It would fit well in something like a stacked or groupedBar chart
, a multiple-lineLine chart
or a stackedRose chart
. However, it can also work well when there's only a single data point like aThermometer chart
.There are a few configuration options for it and you'll most likely need to at least set the colors option.
When you use the formatted tooltips key macro, the color blob can be configured with
css
by utilising theRGraph_tooltipsFormattedKeyColor
css
class. For example:.RGraph_tooltipsFormattedKeyColor { border: 2px solid black; }
-
%{color:red}
%{color:%{property:myColor}}
%{color:%{property:colors[%{index}]}}
This macro is new to version 6.13 and allows you to use a key-like color blob in your tooltip. The different forms of this macro (as shown above) allow you to combine this macro with other macros (eg%{index}
or%{dataset}
which allows you to integrate the macro into your chart. -
%{list}
This macro (new in version 5.27) allows you to easily show an ordered or unorderedhtml
list in your tooltips. There are examples that use this macro in the download archive demos called*-tooltips-list.html
in thedemos/
directory of the download archive. There are two configuration properties that help facilitate this option:Name: tooltipsFormattedlistTypeDescription:With this property you can switch between an unordered list (the default) and an ordered list. Possible values areul
andol
.Default: ulName: tooltipsFormattedListItemsDescription:This should be a two-dimensional array of the list items that are to be shown for all of the tooltips. An example of this property is:tooltipsFormattedListItems: [ ['Bill','Jerry','Berty'], // First tooltip ['Gill','Carrie','Lucy'], // Second tooltip ['Pob','Nobby','Hilda'] // Third tooltip ]
You can usecss
to style this list - for example:.RGraph_tooltip ul#rgraph_formatted_tooltips_list li { text-align: left; color: yellow; }
Default: null
-
%{table}
This macro allows you to easily show a table of information in your tooltips. It could be useful in a situation where the mainBar chart
shows a set of "overview" values and then clicking on each bar shows a set of more in-depth values. There's an example chart that uses this macro in the download archive demos calledbar-tooltips-table.html
There are two configuration properties that help facilitate this option:tooltipsFormattedTableData: [ // Monday (first bars tooltip) [ ['Attempt 1',5,9,6,3,5,6,6], // First row ['Attempt 2',9,6,8,4,8,6,8], // Second row ['Attempt 3',8,6,3,6,5,8,9], // Third row ['Attempt 4',4,8,6,3,3,5,5], // Fourth row ['Attempt 5',1,2,3,4,5,6,7] // Fifth row ], // Tuesday (second bars tooltip) [ ['Attempt 1', 9,8,6,3,5,8,8], // First row ['Attempt 2', 4,8,4,6,8,7,3], // Second row ['Attempt 3', 8,6,3,6,9,9,6], // Third row ['Attempt 4', 8,6,8,3,4,7,4], // Fourth row ['Attempt 5', 8,3,3,1,7,8,7], // Fifth row ['Attempt 6', 8,6,6,9,4,3,2] // Sixth row ], // Wednesday (third bars tooltip) [ ['Attempt 1', 4,8,6,3,4,4,4], // First row ['Attempt 2', 5,8,6,9,5,8,4], // Second row ['Attempt 3', 7,8,5,6,3,2,4], // Third row ['Attempt 4', 6,8,9,6,5,3,6] // Fourth row ], // Thursday (fourth bars tooltip) [ ['Attempt 1', 4,5,6,3,5,8,8], // First row ['Attempt 2', 2,6,6,5,5,8,8], // Second row ['Attempt 3', 8,3,5,8,9,6,5] // Third row ], // Friday (fifth bars tooltip) [ ['Attempt 1', 9,6,5,3,5,6,9], // First row ['Attempt 2', 4,8,6,5,2,5,5] // Second row ], // Saturday (sixth bars tooltip) [ ['Attempt 1', 4,8,6,3,'DNF',8,4], // First row ['Attempt 2', 4,8,6,3,5,2,2], // Second row ['Attempt 3', 8,7,5,4,6,3,5], // Third row ['Attempt 4', 9,6,6,6,4,8,6] // Fourth row ], // Sunday (seventh bars tooltip) [ ['Attempt 1', 1,9,8,5,6,6,6], // First row ['Attempt 2', 1,9,8,5,6,6,6], // Second row ['Attempt 3', 8,6,3,3,5,6,8], // Third row ['Attempt 4', 4,8,6,3,5,5,5], // Fourth row ['Attempt 5', 9,6,3,5,6,9,9] // Fifth row ] ]
As you can see there's a lot of code that's necessary. But if you lay it out well, like the above example, it doesn't have to be overwhelming. You can see this code in action in theBar chart
demo in the archive calledbar-tooltips-table.html
Customising the appearance of the table can be done quite easily usingcss
. The tooltip has thecss
classRGraph_tooltip
remember, so thecss
could be (you can see this in action in thebar-tooltips-table.html
demo):<style> .RGraph_tooltip h2 { margin: 5px; font-style: italic; } .RGraph_tooltip table { border-collapse: collapse; font-family: Verdana; } .RGraph_tooltip thead th { font-style: italic; } .RGraph_tooltip th, .RGraph_tooltip td { padding: 5px; border: 1px solid #ccc; } .RGraph_tooltip td:nth-child(1){ font-style: italic; } .RGraph_tooltip tr:nth-child(2n+2) td:nth-child(1n+2){ background-color: #eee; } .RGraph_tooltip tr:nth-child(2n+1) td:nth-child(1n+2){ background-color: #ddd; } </style>
demos/
folder of the download archive
that show tooltip templates:
bar-tooltips-formatted-table.html
hbar-tooltips-formatted-table.html
line-tooltips-formatted-table.html
thermometer-tooltips-formatted-table.html
Using custom properties with your tooltips
By using custom properties in your chart configuration you can pass in more data to your chart
which the tooltips can then use. This is shown in the chart above with the myNames
property - the full chart code is:
new RGraph.Bar({
id: 'cvs_tooltip_templates',
data: [[5,3],[9,1],[6,6],[5,9],[5,5],[4,3],[5,9]],
options: {
colors: ['Gradient(#faa:red)','Gradient(#aaf:blue)'],
xaxisLabels: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
xaxis: false,
yaxis: false,
backgroundGridBorder: false,
backgroundGridVlines: false,
myNames: ['Dave','Richard'],
tooltips: 'Score for %{property:myNames[%{index}]} on %{property:xaxisLabels[%{dataset}]}: %{value}kg'
}
}).draw();
The custom properties can be strings, numbers or arrays. The example above shows an array.
Formatted tooltips will help you generate tooltips that have the data from your chart embedded in them and enhance the abilities of RGraph significantly.