I've created a US choropleth map in D3. There are two layers; the first is a state layer that simply has blank states. The second layer is a county layer that colors the counties based on data. I have also created a tooltip to show the data.
There are, however, a few states for which I have no data. I either want for there to be no tooltip at all for those states; or alternatively, the tooltip could just say something like "no data available."
This is what my map looks like:
This is what the tooltip looks like for a county with data:
This is what the tooltip looks like when it hits a null value:
It's that last one that I want to fix.
Here is the code for the tooltip, where I tried to create an alternative tooltip:
// add tooltip
const tip = d3.tip()
.attr('class', 'tooltip-container')
.html(d => {
let content = `<div class="tooltip-left"><strong>County: </strong><span class="tooltip-right">${countyNames[d.id]}</span></div>`;
content += `<div class="tooltip-left"><strong>Avg Prem: </strong><span class="tooltip-right">$ ${premById[d.id]}</span></div>`;
return content;
})
svg.call(tip);
// add null tooltip
const null_tooltip = d3.tip()
.attr('class', 'tooltip-container')
.html(d => {
let content = `<div class="tooltip-left"><strong>No Data Available</strong></div>`;
return content;
})
svg.call(null_tooltip);
// add events
svg.selectAll('path')
// mouse hover event
.on('mouseover', (d, i, n) => {
if (i){
tip.show(d,n[i]);
// handleMouseOver(d,i,n);
}
else {
null_tooltip.show();
}
})
This doesn't work at all, but I'm quite confused how to create an if-else statement that might test for a null value here. Or alternatively, if there's just a way to not trigger the tooltip code for the nulls?
I have more experience in Python than JS and I know there are easy ways to do this in Python; not sure about JS.
Edit: Solved; see below. Basically, I realized that the FIPS codes are 5 digits for counties, but only 2 digits for states. I then used "d.id.length" in the if statement and required it to be greater than 4. Might still be a better solution, and this one avoided the "null value" issue, but it works in this case.