D3.js如何使用折线图在我的图例中添加工具提示

D3.js How to add tooltip in my legend using line graph

本文关键字:添加 工具提示 我的 js 何使用 折线图 D3      更新时间:2023-09-26

我使用 D3 绘制折线图.js我在折线图中使用工具提示,但我也在图例中使用工具提示,但启用以图例显示工具提示,我编写了给定的代码,可以在图例中显示工具提示。

   var dates=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
var legend = canvas.append("g")
    .attr("class", "legend")
   // .attr("transform", "translate(70,10)");
var legendRect = legend.selectAll('rect').data(dates);
legendRect.enter()
    .append("rect")
    .attr("x", function (d,i){return i*14;})
    .attr("width", 12)
    .attr("height", 20)
    .attr("y", 10)
    .style("fill","steelblue")
 legend.selectAll("text")
.data(dates)
.enter()
.append("text")  
.attr("x", function (d,i){return i*14;}) 
.attr("y", 25)
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white")
.text(function(d) {
return d;
})
.on("mouseover", function(d) {      
            div.transition()        
                .duration(200)      
                .style("opacity", .9);      
            div .html(formatTime(d.key) + "<br/>"  + d.value)  
                .style("left", (d3.event.pageX) + "px")     
                .style("top", (d3.event.pageY-28) + "px");    
            })                  
        .on("mouseout", function(d) {       
            div.transition()        
                .duration(500)      
                .style("opacity", 0);   
        });
Iam adding tooltip in text but enable to show the tooltip in my values(I have only problem in legend tooltip)

查看此代码。它完全符合您的要求。

这也是一个很好的例子。