鼠标移到d3.js中链接和节点的事件上应该显示文本

Mouse over events for links and nodes in d3.js should display texts

本文关键字:事件 文本 显示 节点 d3 js 链接 鼠标      更新时间:2023-09-26

JSON HTML页面数据如下:

   var IDData = JSON.stringify([["node/105173", "node/38180995", "Agent", "Customer", "1379644.0", 1, 264.0, "1374903"], ["node/1061", "node/21373542", "Agent", "Customer", "530848.0", 1, 3000.0, "529502"]....]

数组的长度不同,但数组中元素的位置始终相同。

下面是我的d3.js代码:

function createNodes (IDData) {
   var nodes = [{group:1, group: 1}]; 
   var links = [];
   IDData.forEach(function(item){
   nodes.push({id: item, group: 1})
   links.push({source: item, target: item, value: 1}) // ;
  });  
  var d3GraphData = {
     nodes: nodes,
     links: links,
     startnodetype: startnodetype, //
     endnodetype: endnodetype,    right way to pass them to makeGraph()?
     PayTime: PayTime,
     TXN_COUNT: TXN_COUNT,
     Total_Amt: Total_Amt,
     SendTime: SendTime        //
  }
return d3GraphData;
 };

function makeGraph (selector, d3GraphData) {
    var svg = d3.select(selector),
    width = +svg.attr("width"),
    height = +svg.attr("height");
 var color = d3.scaleOrdinal(d3.schemeCategory20);
 var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));
 var link = svg.append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(d3GraphData.links)
    .enter()
    .append("line")
    .attr("stroke-width", function(d) { return Math.sqrt(d.value); })
    .on("mouseover",mouse_link);  // calling mouseover function for links
 var node = svg.append("g")
     .attr("class", "nodes")
     .selectAll("circle")
     .data(d3GraphData.nodes)
     .enter()
     .append("circle")
     .attr("r", 5)
     .attr("fill", function(d) { return color(d.group); })
     .call(d3.drag()
     .on("start", dragstarted)
     .on("drag", dragged)
     .on("end", dragended)
)
 .on("mouseover",mouse_node);   //calling the mouseover function for nodes
  node.append("title")
    .text(function(d) { return d.id; });
 simulation
   .nodes(d3GraphData.nodes)
   .on("tick", ticked);
 simulation.force("link")
   .links(d3GraphData.links);
function ticked() {
  link
    .attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });
 node
   .attr("cx", function(d) { return d.x; })
   .attr("cy", function(d) { return d.y; });
      }
 function dragstarted(d) {
     if (!d3.event.active) simulation.alphaTarget(0.3).restart();
     d.fx = d.x;
     d.fy = d.y;
       }
 function dragged(d) {
   d.fx = d3.event.x;
   d.fy = d3.event.y;
     }
 function dragended(d) {
      if (!d3.event.active) simulation.alphaTarget(0);
       d.fx = null;
       d.fy = null;
 }
 function mouse_node() {// function to handle mouse_over events on nodes
         d3.select(this).transition()
              .style("left", "20px")
              .style("top", "20px")
              .attr("r",30)
              .style("fill","lightsteelblue")
              .text(d.startnodetype or d.endnodetype); //how do I select the nodetype depending on whether it is the start node or end node?
 function mouse_link(){/// mouse over event on links
       d3.select(this).transition()
            .duration(750)
            .style("left", "20px")
            .style("top", "20px")
            .attr("r",30)
            .style("fill","lightsteelblue")
            .text(d.PayTime)
            .text(d.TXN_COUNT)
            .text(d.Total_Amt)
            .text(d.Send_Time)  // right way to display the texts?


$(document ).ready(function() {
    console.log(IDData);
    var galData = JSON.parse(IDData);
    var startnodes = [];
    var endnodes = [];
    var nodetype1 = [];
    var nodetype2 = [];
    var PayTime = [];
    var TXN_COUNT = [];
    var Total_Amt = [];
    var SendTime = [];
galData.map(function(e,i){
   startnodes.push(e[0]);
   endnodes.push(e[1]);
   nodetype1.push(e[2]);
   nodetype1.push(e[3]);
   PayTime.push(e[4]);
   TXN_COUNT.push(e[5]);
   Total_Amt.push(e[6]);
   SendTime.push(e[7]);
     });
  var final_data createNodes(startnodes,endnodes,startnodetype,endnodetype,PayTime,TXN_COUNT,Total_Amount,SendTime);                           
  makeGraph("#Network_graph",final_nodes)
  });

另外,在我的HTML页面中,当节点或链接被点击时,div显示相关文本:

    <div id="graph"></div>
    < div id = "text"</div? 

文本是更好的方法还是工具提示?如何将这个div连接到d3.js?我想到了文本,因为我想让它成为HTML主体的一部分。

我从来没有在javascript或d3.js工作过。如果粘贴了太多代码,请道歉。我确实阅读并理解了如何以及在哪里使用事件函数。但仍然不确定是否以上是正确的方式来实现它。特别是当来自源的JSON数据不是固定大小时。

文本是更好的方法还是工具提示?

这是基于意见的,最好不要在SO中解决。

如何连接这个div到d3.js?

由于您的<div>有一个ID,因此只需在click事件上更改其内容即可。

这是一个非常基本的演示。首先,我们选择div:

var div = d3.select("#text");

我们设置一个click事件到圆圈,使用匿名函数中的第一个参数来访问数据:

circles.on("click", function(d){
    div.html("This circle is named " + d.name);
});

因此,您必须为您的节点和链接编写类似的代码。

下面是演示:

var data = [{name: "foo", size: 20, colour: "blue"},
            {name: "bar", size: 30, colour: "green"},
            {name: "baz", size: 15, colour: "red"}];
var svg = d3.select("body")
  .append("svg")
  .attr("width", 300)
  .attr("height", 100);
var div = d3.select("#text");
var circles = svg.selectAll(".circles")
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("cx", function(d,i){ return 50 + i*100})
  .attr("r", function(d){ return d.size})
  .attr("fill", function(d){ return d.colour});
circles.on("click", function(d){
 div.html("This circle is named " + d.name);
  });
circle {
  cursor: pointer;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="text">Click the circle to see its name</div>

PS:你说"点击节点或链接时显示相关文本",但你的题目说"鼠标悬停"。上面的演示使用click,但mouseover的原理是相同的。使用mouseover检查演示:

var data = [{name: "foo", size: 20, colour: "blue"},
            {name: "bar", size: 30, colour: "green"},
            {name: "baz", size: 15, colour: "red"}];
var svg = d3.select("body")
  .append("svg")
  .attr("width", 300)
  .attr("height", 100);
var div = d3.select("#text");
var circles = svg.selectAll(".circles")
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("cx", function(d,i){ return 50 + i*100})
  .attr("r", function(d){ return d.size})
  .attr("fill", function(d){ return d.colour});
circles.on("mouseover", function(d){
 div.html("This circle is named " + d.name);
  }).on("mouseout", function(){
  div.html("Hover the circle to see its name");
  });
circle {
  cursor: pointer;
  }
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="text">Hover the circle to see its name</div>