javascript - 在饼图中使用鼠标悬停并在 d3 v3 js 中显示标签

标签 javascript d3.js charts

嗨,我是 d3js 新手,所以我无法在饼图的给定代码中使用鼠标悬停事件...我有一个 id 名为图表的类,那么如何创建一些鼠标悬停事件并显示标签的类?

这是我用来绘制饼图的代码:

var w = 300;
var h = 300;

var dataset =  [
  {"year":"2017-07-01","value":"5"},
  {"year":"2017-07-02","value":"10"},
  {"year":"2017-07-03","value":"15"},
  {"year":"2017-07-04","value":"20"},
  {"year":"2017-07-05","value":"25"},
  {"year":"2017-07-06","value":"30"},
  {"year":"2017-07-07","value":"35"},
  {"year":"2017-07-08","value":"40"},
  {"year":"2017-07-09","value":"45"},
  {"year":"2017-07-10","value":"50"},
  {"year":"2017-07-11","value":"55"},
  {"year":"2017-07-12","value":"60"},
  {"year":"2017-07-13","value":"65"},
  {"year":"2017-07-14","value":"70"}
];

var outerRadius = w / 2;
var innerRadius = 0;
var arc = d3.svg.arc()
  .innerRadius(innerRadius)
  .outerRadius(outerRadius);

var pie = d3.layout.pie()
  .value(function(d) {
    return d.value;
  });

var color = d3.scale.category20();

var svg = d3.select("#chart")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var arcs = svg.selectAll("g.arc")
  .data(pie(dataset))
  .enter()
  .append("g")
  .attr("class", "arc")
  .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");

arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc);

arcs.append("text")
  .attr("transform", function(d) {
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("text-anchor", "middle")
  .text(function(d) {
    return d.value;
  });

最佳答案

我使用工具提示:

var popup=d3.select("body").append("div").attr("class","tooltip").style("opacity",0);

然后调用工具提示,向节点添加一个事件监听器(我猜这对你来说是弧线,但我还没有做过饼图):

nodes.on("mouseover", fade(.1,"over")).on("mouseout",fade(.8,"out"));

然后将工具提示放置在节点(或本例中为饼图)附近的函数:

function fade (opacity, event){
return function (d){
    if(event === "over"){
    popup.transition().duration(100).style("opacity", .9).style("display", "inline-block");
    popup.html("Year: " + d.year + "</br> Value: " + d.value)
    .style("left", (d3.event.pageX + 20) + "px")
    .style("top", (d3.event.pageY - 20) + "px");
    d3.select(this).classed("node-mouseover", true);}
else if(event==="out"){
    popup.transition().duration(100).style("opacity",0);
    d3.select(this).classed("node-mouseover",false);

}}}

还有其他方法可以做到这一点,但这似乎很受欢迎this example是类似的。

编辑:查看 bl.ocks.org了解更多示例。

关于javascript - 在饼图中使用鼠标悬停并在 d3 v3 js 中显示标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45559499/

相关文章:

javascript - d3 鼠标悬停时绘制一次

svg - 将任意数据附加到 D3.js 中的对象

charts - Tableau - 日复一日的多线图

javascript - 解析图表 js laravel Blade 中的数组

PHP:如何删除/替换特定的 href 属性值

javascript - 在 MarkerClustererOptions 的 MarkerClustererPlus 样式参数中无法正常工作

Javascript - 如何获取文本框中的字符数并使用子字符串删除

d3.js - d3自动空间重叠刻度标签

javascript - 谷歌图表无法正常工作而不引发异常

javascript - 跨多个子域的 WebAuthn