首页 > 解决方案 > 条形图和数据之间的共享工具提示未在 D3 堆栈条形图中成功呈现

问题描述

我正在使用 d3-tip.js 向堆叠条形图添加工具提示。我的工具提示的预期输出应该是当鼠标悬停到栏的特定堆栈时,工具提示将显示该特定堆栈的人口。如下图所示,每个条上的每个堆栈代表一个性别,男性或女性。条形上方的数字是男性和女性人口的总和。现在我希望工具提示显示每个性别的个体人口。但是,我的实现中有 3 个问题:

  1. 数据似乎没有渲染成功,如下图所示,数据没有成功渲染。

  2. 第二个问题是栏之间共享的工具提示。例如,如下图所示,当我的鼠标在未知关系的“女性”(粉红色)堆栈上时,您可以看到“未知”栏和“其他”栏的堆栈都被突出显示,所以看起来像他们跨栏共享相同的工具提示。

在此处输入图像描述

  1. 工具提示显示的位置不正确。如下图,当我的鼠标在Other的Male(蓝色)堆栈上时,tooltip的位置不在“Other”上,而是在“unknown”栏上。

在此处输入图像描述

下面是添加工具提示的代码:

var tip = d3.tip()
           .attr('class', "d3-tip")
           .style("color", "white")
           .style("background-color", "black")
           .style("padding", "6px")
           .style("border-radius", "4px")
           .style("font-size", "12px")
           .offset([-10, 0])
           .html(function(d) { return `<strong>${d3.format(',')(keys, d => z(d.key))}</strong> population`; });

       svg.call(tip);

       svg
         .selectAll('g.layer')
         .on('mouseover', function(d) {
         // show the tooltip on mouse over
         tip.show(d, this);
         // when the bar is mouse-overed, we slightly decrease opacity of the bar.
         d3.select(this).style('opacity', 0.7);
         }) 
         .on('mouseout', function(d) { 
         // hide the tooltip on mouse out
         tip.hide();
         d3.select(this).style('opacity', 1)
       });

这是我在 Plunker 中的图表的现场演示的链接:

http://plnkr.co/edit/6xB2Kzi46hWL37UjlgTs?p=preview

标签: javascripthtmlcssd3.jsdata-visualization

解决方案


推荐阅读