我试图在工具提示中添加一个简单的条形图;它由2个变量组成 - 男人和女人。我希望有人能够帮我把它放在工具提示里面而不是把它附加到当前被追加的位置。我已经给了这个特殊的区域,只是为了让我知道它实际上正在出现(它是),但我不知道如何将其纳入工具提示。任何帮助深表感谢。哦,这需要在d3中完成,这与我提出这个问题的原因不同 - 我看到一个类似的问题在纯d3中没有实现,我无法完全遵循继续在这个例子中模仿它。
.on("mouseover", function(d)
{
tip.show(d);
var state = d.properties.name;
var men = d.properties.men;
var women = d.properties.women;
var dataset = [men, women];
var barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([0, width/2]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * dataset.length);
var bar = chart.selectAll("g")
.data(dataset)
.enter().append("g")
.attr("transform", function(d, i)
{
return "translate(0," + i * barHeight + ")";
});
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d)
{
return x(d)/2+5;
})
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d)
{
return "$" + d;
});
})
答案 0 :(得分:1)
由于您没有共享整个代码来创建图表,因此这个答案只会处理您的问题标题:
我不是d3.tip()
用户,因为我创建了自己的工具提示。但是你想要的并不复杂:由于工具提示是<div>
元素,你绝对可以在其中添加一个SVG。
但是,您必须知道 where 才能创建SVG。因此,在以下演示中,我创建了此d3.tip
工具提示:
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 120])
.html("<p>This is a SVG inside a tooltip:</p>
<div id='tipDiv'></div>");
//div ID here --^
这里的重要部分是:d3.tip div中有一个内部<div>
,带有一个给定的ID(在这种情况下,tipDiv
)。我将使用该ID在工具提示中创建我的SVG:
selection.on('mouseover', function(d) {
tool_tip.show();
var tipSVG = d3.select("#tipDiv")
//select the div here--^
.append("svg")
//etc...
})
以下是演示:
var svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 120])
.html("<p>This is a SVG inside a tooltip:</p><div id='tipDiv'></div>");
svg.call(tool_tip);
var data = [14, 27, 19, 6, 17];
var circles = svg.selectAll("foo")
.data(data)
.enter()
.append("circle");
circles.attr("cx", 50)
.attr("cy", function(d, i) {
return 20 + 50 * i
})
.attr("r", function(d) {
return d
})
.attr("fill", "teal")
.on('mouseover', function(d) {
tool_tip.show();
var tipSVG = d3.select("#tipDiv")
.append("svg")
.attr("width", 200)
.attr("height", 50);
tipSVG.append("rect")
.attr("fill", "steelblue")
.attr("y", 10)
.attr("width", 0)
.attr("height", 30)
.transition()
.duration(1000)
.attr("width", d * 6);
tipSVG.append("text")
.text(d)
.attr("x", 10)
.attr("y", 30)
.transition()
.duration(1000)
.attr("x", 6 + d * 6)
})
.on('mouseout', tool_tip.hide);
&#13;
.d3-tip {
line-height: 1;
padding: 6px;
background: wheat;
border-radius: 4px solid black;
font-size: 12px;
}
p {
font-family: Helvetica;
}
&#13;
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<p>Hover over the circles:</p>
&#13;