Advertisement
Guest User

Untitled

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