在 d3.js 折线图中永久显示工具提示

Displaying tooltips permanently in d3.js line chart

本文关键字:显示 工具提示 d3 js 折线图      更新时间:2023-09-26

我正在使用d3.js制作折线图。鼠标悬停时显示某个点的工具提示,鼠标悬停时消失。我想在创建图表时永久显示所有工具提示。有没有办法做到这一点?

我的脚本-

var x = d3.time.scale().range([0, w]);
var y = d3.scale.linear().range([h, 0]);    
x.domain(d3.extent(data, function(d) { return d.x; }));
y.domain(d3.extent(data, function(d) { return d.y; }));
var line = d3.svg.line()
  .x(function(d) { 
     return x(d.x); 
  })
  .y(function(d) { 
     return y(d.y); 
  })
var div = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0);
var graph = d3.select("#graph").append("svg:svg")
           .attr("width", 900)
           .attr("height", 600)
           .append("svg:g")
           .attr("transform", "translate(" + 80 + "," + 80 + ")");

 var xAxis = d3.svg.axis().scale(x).ticks(10).orient("bottom");
 var yAxisLeft = d3.svg.axis().scale(y).ticks(10).orient("left");
 var area = d3.svg.area()
.x(function(d) { return x(d.x); })
.y0(h)
.y1(function(d) { return y(d.y); });
graph.selectAll("circle")
     .data(data)
     .enter()
     .append("circle")
     .attr("class", "circle")
     .attr("cx", function (d) { return x(d.x); })
     .attr("cy", function (d) { return y(d.y); })
     .attr("r", 4.5)
     .style("fill", "black")
     .on("mouseover", function(d) {
     div.transition()
     .duration(200)
     .style("opacity", .9);
     div
     .html(d.y) + "<br/>" + d.x)
     .style("left", (d3.event.pageX) + "px")
     .style("top", (d3.event.pageY - 30) + "px");
     })
     .on("mouseout", function(d) {
     div.transition()
     .duration(500)
     .style("opacity", 0); 
     });

要标记每个数据点,可以在适当的位置添加text元素。代码看起来像这样。

graph.selectAll("text").data(data).enter()
     .append("text")
     .attr("x", function (d) { return x(d.x); })
     .attr("y", function (d) { return y(d.y) - 10; })
     .text(function(d) { return d.value; });