script.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var svg = d3.select("svg"),
  2. width = +svg.attr("width"),
  3. height = +svg.attr("height");
  4. var color = d3.scaleOrdinal(d3.schemeCategory20);
  5. var simulation = d3.forceSimulation()
  6. .force("link", d3.forceLink().id(function(d) { return d.id; }))
  7. .force("charge", d3.forceManyBody())
  8. .force("center", d3.forceCenter(width / 2, height / 2));
  9. d3.json("miserables.json", function(error, graph) {
  10. if (error) throw error;
  11. var link = svg.append("g")
  12. .attr("class", "links")
  13. .selectAll("line")
  14. .data(graph.links)
  15. .enter().append("line")
  16. .attr("stroke-width", function(d) { return Math.sqrt(d.value); });
  17. var node = svg.append("g")
  18. .attr("class", "nodes")
  19. .selectAll("text")
  20. .data(graph.nodes)
  21. .enter().append("text")
  22. .text(function(d) { return d.id; })
  23. .attr("fill", function(d) { return color(d.group); })
  24. .call(d3.drag()
  25. .on("start", dragstarted)
  26. .on("drag", dragged)
  27. .on("end", dragended));
  28. simulation
  29. .nodes(graph.nodes)
  30. .on("tick", ticked);
  31. simulation.force("link")
  32. .links(graph.links);
  33. function ticked() {
  34. link
  35. .attr("x1", function(d) { return d.source.x; })
  36. .attr("y1", function(d) { return d.source.y; })
  37. .attr("x2", function(d) { return d.target.x; })
  38. .attr("y2", function(d) { return d.target.y; });
  39. node
  40. .attr("x", function(d) { return d.x; })
  41. .attr("y", function(d) { return d.y; });
  42. }
  43. });
  44. function dragstarted(d) {
  45. if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  46. d.fx = d.x;
  47. d.fy = d.y;
  48. }
  49. function dragged(d) {
  50. d.fx = d3.event.x;
  51. d.fy = d3.event.y;
  52. }
  53. function dragended(d) {
  54. if (!d3.event.active) simulation.alphaTarget(0);
  55. d.fx = null;
  56. d.fy = null;
  57. }