In the following tutorial, we will learn how to use a third-party tooltip library with Plottable.
No tooltip library is bundled with Plottable. Instead, Plottable is flexible enough to use with the tooltip library of your choice. In this tutorial We will show how to use Bootstrap to create tooltips in bar charts and line charts.
First we create a basic bar chart.
// Code for rendering a bar chart
var data = [
{ x: 1, y: 5 },
{ x: 2, y: 8 },
{ x: 3, y: 7 }
];
var xScale = new Plottable.Scales.Category();
var yScale = new Plottable.Scales.Linear();
var plot = new Plottable.Plots.Bar()
.x(function(d) { return d.x; }, xScale)
.y(function(d) { return d.y; }, yScale)
.addDataset(new Plottable.Dataset(data))
.renderTo("svg#example");
Then we create an anchoring element and attach the tooltip to it.
// Initializing tooltip anchor
var tooltipAnchorSelection = plot.foreground().append("circle").attr({
r: 3,
opacity: 0
});
var tooltipAnchor = $(tooltipAnchorSelection.node());
tooltipAnchor.tooltip({
animation: false,
container: "body",
placement: "auto",
title: "text",
trigger: "manual"
});
We bind a Pointer
Interaction
to the Plot
to position, show, and hide the tooltip.
// Setup Interaction.Pointer
var pointer = new Plottable.Interactions.Pointer();
pointer.onPointerMove(function(p) {
var closest = plot.entityNearest(p);
if (closest) {
tooltipAnchorSelection.attr({
cx: closest.position.x,
cy: closest.position.y,
"data-original-title": "Value: " + closest.datum.y
});
tooltipAnchor.tooltip("show");
}
});
pointer.onPointerExit(function() {
tooltipAnchor.tooltip("hide");
});
pointer.attachTo(plot);
Finally, we add a CSS class to keep the tooltip itself from blocking the interaction:
.tooltip {
pointer-events: none;
}
And there you have it! If you hover over the rectangles in your bar plot, tooltips will appear.
The full code for this example is here:
The same technique can be used for line charts: we create a basic chart and a tooltip anchor, then attach a pointer interaction.
The full code for this example is here: