我正在使用流行的提示库 d3-tip.js,可以在 here 找到它的示例。 。通常,提示包含动态定义的文本,如下所示:
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
html = "";
html += "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
return html;
})
但是,假设我有一个这样的传奇:
var legend = g.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(keys.slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", z);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) { return d; });
我想以某种方式在 d3 toollip 内附加一个小的 svg 矩形。这样,当您将鼠标悬停在具有不同类别的图表(即分组条形图)上时,除了 html 文本之外,工具提示还将具有匹配颜色的 svg 矩形。理想情况下,使用现有的图例变量,如上所示。
如果不可能,请解释原因,我也可以接受这个答案。
最佳答案
在 d3.tip
工具提示中创建 SVG 很容易。实际上,您只需使用与任何其他 D3 创建的 SVG 相同的逻辑:选择容器并将 SVG 附加到其中。
在下面的演示中,我将在您的 var Tip
中创建一个具有给定 ID 的空 div。在本例中,div 的 ID 名为 mySVGtooltip
:
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 40])
.html("<div id='mySVGtooltip'></div>");
之后,只需在 mouseover
事件中按 ID 选择该 div 并将 SVG 附加到它即可:
var legendSVG = d3.select("#mySVGtooltip")
.append("svg")
.attr("width", 160)
.attr("height", 50);
这是演示,将鼠标悬停在圆圈上:
var svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 40])
.html("<div id='mySVGtooltip'></div>");
svg.call(tool_tip);
var data = [20, 10, 30, 15, 35];
var circles = svg.selectAll(null)
.data(data)
.enter()
.append("circle");
circles.attr("cy", 50)
.attr("cx", function(d, i) {
return 30 + 55 * i
})
.attr("r", function(d) {
return d
})
.attr("fill", "lightgreen")
.attr("stroke", "dimgray")
.on('mouseover', function(d) {
tool_tip.show();
var legendSVG = d3.select("#mySVGtooltip")
.append("svg")
.attr("width", 160)
.attr("height", 50);
var legend = legendSVG.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10);
legend.append("text")
.attr("x", 80)
.attr("text-anchor", "middle")
.attr("y", 16)
.attr("font-size", 14)
.text("Age Group:");
legend.append("rect")
.attr("y", 25)
.attr("x", 10)
.attr("width", 19)
.attr("height", 19)
.attr("fill", "goldenrod");
legend.append("text")
.attr("x", 35)
.attr("y", 40)
.text(function() {
return d + " years and over";
});
})
.on('mouseout', tool_tip.hide);
.d3-tip {
line-height: 1;
background: gainsboro;
border: 1px solid black;
font-size: 12px;
}
p {
font-family: Helvetica;
}
<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>
请注意,在这个非常简单的演示中,我使用通过 mouseover
事件传递给匿名函数的数据 (d
)。我在你的问题中看到你有自己的数据。因此,相应地更改我的演示中的代码。
关于javascript - 在 d3tip 工具提示中嵌入 svg 形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427544/