【问题标题】:Use mouseover in pie chart and show label in d3 v3 js在饼图中使用鼠标悬停并在 d3 v3 js 中显示标签
【发布时间】:2017-08-08 04:50:18
【问题描述】:

您好,我是 d3js 的新手,所以我无法在饼图的给定代码中使用 mouseover 事件...我有一个名为 chart 的带有 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;
  });

【问题讨论】:

  • 您要显示什么标签?饼图中的切片已经具有的值?还是其他标签?当用户将鼠标悬停在切片上或用户将鼠标悬停在整个饼上时?你看,要获得适当的帮助,你必须准确地解释你的想法。 “我想显示一个标签” 很模糊。
  • 我必须在鼠标悬停时显示年份
  • 好吧,我就放弃了。祝你好运。

标签: javascript d3.js charts


【解决方案1】:

我使用工具提示:

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 了解更多示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多