Advertisement
Guest User

Untitled

a guest
May 9th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.20 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <style>
  4.  
  5. .links line {
  6.   stroke: #999;
  7.   stroke-opacity: 0.6;
  8. }
  9.  
  10. .nodes circle {
  11.   stroke: #fff;
  12.   stroke-width: 1.5px;
  13. }
  14.  
  15. </style>
  16. <svg width="960" height="600"></svg>
  17. <script src="https://d3js.org/d3.v4.min.js"></script>
  18. <script>
  19.  
  20. var svg = d3.select("svg"),
  21.     width = +svg.attr("width"),
  22.     height = +svg.attr("height");
  23.  
  24. var color = d3.scaleOrdinal(d3.schemeCategory20);
  25.  
  26. var simulation = d3.forceSimulation()
  27.     .force("link", d3.forceLink().id(function(d) { return d.id; }))
  28.     .force("charge", d3.forceManyBody())
  29.     .force("center", d3.forceCenter(width / 2, height / 2));
  30.  
  31.  
  32. d3.json("graphdata.json", function(error, graph) {
  33.   if (error) throw error;
  34.  
  35.   var link = svg.append("g")
  36.       .attr("class", "links")
  37.     .selectAll("line")
  38.     .data(graph.links)
  39.     .enter().append("line")
  40.       .attr("stroke-width", function(d) { return Math.sqrt(d.value); });
  41.  
  42.   var node = svg.append("g")
  43.       .attr("class", "nodes")
  44.     .selectAll("circle")
  45.     .data(graph.nodes)
  46.     .enter().append("circle").attr("r", function(d) { return 100; })
  47.       .attr("r", 10)
  48.       .attr("fill", function(d) { return color(d.group); })
  49.       .call(d3.drag()
  50.           .on("start", dragstarted)
  51.           .on("drag", dragged)
  52.           .on("end", dragended));
  53.  
  54.   node.append("title")
  55.       .text(function(d) { return d.id; });
  56.  
  57.   simulation
  58.       .nodes(graph.nodes)
  59.       .on("tick", ticked);
  60.  
  61.   simulation.force("link")
  62.       .links(graph.links);
  63.  
  64.   function ticked() {
  65.     link
  66.         .attr("x1", function(d) { return d.source.x; })
  67.         .attr("y1", function(d) { return d.source.y; })
  68.         .attr("x2", function(d) { return d.target.x; })
  69.         .attr("y2", function(d) { return d.target.y; });
  70.  
  71.     node
  72.         .attr("cx", function(d) { return d.x; })
  73.         .attr("cy", function(d) { return d.y; });
  74.   }
  75. });
  76.  
  77. function dragstarted(d) {
  78.   if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  79.   d.fx = d.x;
  80.   d.fy = d.y;
  81. }
  82.  
  83. function dragged(d) {
  84.   d.fx = d3.event.x;
  85.   d.fy = d3.event.y;
  86. }
  87.  
  88. function dragended(d) {
  89.   if (!d3.event.active) simulation.alphaTarget(0);
  90.   d.fx = null;
  91.   d.fy = null;
  92. }
  93.  
  94. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement