Advertisement
Guest User

Untitled

a guest
May 6th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. d3.json('/data/bvg-graph.json', function(json){
  2.  
  3. var width = 740,
  4. height = 600;
  5.  
  6. var svg = d3.select('svg')
  7. .style("display", "block")
  8. .attr('width', width)
  9. .attr('height', height);
  10.  
  11. // draw the graph edges
  12. var link = svg.selectAll("line.link")
  13. .data(json.links)
  14. .enter().append("line")
  15. .style('stroke','black');
  16.  
  17. // draw the graph nodes
  18. var node = svg.selectAll("circle.node")
  19. .data(json.nodes)
  20. .enter()
  21. .append("circle")
  22. .attr("class", "node")
  23. .style("fill",function(d) {
  24. // custom colours based on train type
  25. if (d.name.match(/^S\+U/)) {
  26. return 'rgb(215,49,58)';
  27. }
  28. else if (d.name.match(/^U/)) {
  29. return 'rgb(0,114,171)';
  30. }
  31. else {
  32. return 'green';
  33. }
  34. })
  35. .attr("r", 12);
  36.  
  37. var nodename = svg.selectAll("text.nodename")
  38. .data(json.nodes)
  39. .enter()
  40. .append("text")
  41. .text(function(d) {return d.name});
  42.  
  43. // create the layout
  44. var force = d3.layout.force()
  45. .charge(-250)
  46. .linkDistance(function(d,e) {
  47. var distance = 1.5*parseFloat(d.distance)/10 - 5;
  48. return (isNaN(distance)) ? 10 : distance; })
  49. .size([width, height])
  50. .nodes(json.nodes)
  51. .links(json.links)
  52. .start();
  53.  
  54.  
  55. // define what to do one each tick of the animation
  56. force.on("tick", function() {
  57. link.attr("x1", function(d) { return d.source.x; })
  58. .attr("y1", function(d) { return d.source.y; })
  59. .attr("x2", function(d) { return d.target.x; })
  60. .attr("y2", function(d) { return d.target.y; });
  61.  
  62. node.attr("cx", function(d) { return d.x; })
  63. .attr("cy", function(d) { return d.y; });
  64.  
  65. nodename.attr("x", function(d) { return d.x - 3; })
  66. .attr("y", function(d) { return d.y + 4; });
  67. });
  68.  
  69. // precalculate force layout ticks for more natural appearance
  70. var k = 0;
  71. while ((force.alpha() > 1e-2) && (k < 40)) {
  72. force.tick(),
  73. k = k + 1;
  74. }
  75. // bind the drag interaction to the nodes
  76. node.call(force.drag);
  77.  
  78. // misc stuff for auto resizing svg
  79. function updateWindow(){
  80. $("svg").width($(".site").width());
  81. }
  82. window.onresize = updateWindow;
  83.  
  84. if ($(".site").width() < 740) {
  85. updateWindow();
  86. }
  87.  
  88. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement