Next, we will build the tooltip. To be precise, we will build the static part of the tooltip, that is, the bar chart. We will add the changing parts such as the header information and the red indicator as soon as we hover over the country. First, we twist the data into the right shape, and then we build a simple bar chart:
function buildTooltip(data) {
var forestsByPercent = data
.slice()
.sort(function(a, b) {
return d3.descending(+a.percent, +b.percent);
})
.map(function(el) {
return {
country: el.country,
percent: +el.percent,
color: colorScale(+el.percent)
};
});
var countryList = forestsByPercent.map(function(el) {
return el.country;
});
The data we pass into this function is—you guessed it—our forestry-boosted countries' GeoJSON. forestsByPercent is just a sorted array of objects holding the data we need for the bar chart. countryList is just an array of (also sorted) countries we will use as an extension to our ordinal scale. The following is the resulting bar chart:
var tipWidth = 200,
tipHeight = 200;
var xScale = d3.scaleLinear()
.domain([0, 1])
.range([0, tipWidth]);
var yScale = d3.scaleBand()
.domain(countryList)
.rangeRound([0, tipHeight]);
svg = d3.select('svg#tip-visual')
.attr('width', tipWidth)
.attr('height', tipHeight);
svg.selectAll('.bar')
.data(forestsByPercent)
.enter().append('rect')
.attr('class', 'bar')
.attr('id', function(d) { return stripString(d.country); })
.attr('x', xScale(0))
.attr('y', function(d) { return yScale(d.country); })
.attr('width', function(d) { return xScale(d.percent); })
.attr('height', yScale.bandwidth())
.attr('fill', function(d) { return d.color; });
} // buildTooltip()
That was simple. By the way, we build all our interactive tooltip functions in the ready() function. This way, we have access to all the data we need and have it all nicely cordoned off from any outside JavaScript scopes. In real life, it might be worth considering outsourcing interactivity to its own module to keep concerns separate.
We call this buildTooltip() function in ready() after defining an svg variable we can address from the other two tooltip functions, tooltipShow() and tooltipHide() which we will build next.
var svg;
buildTooltip(forests);