概要 实例 介绍 源码

流图

源文件:index.html

  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <title>Streamgraph</title>
  4. <style>
  5. button {
  6. position: absolute;
  7. left: 10px;
  8. top: 10px;
  9. }
  10. </style>
  11. <button onclick="transition()">Update</button>
  12. <svg width="960" height="500"></svg>
  13. <script src="https://d3js.org/d3.v4.min.js"></script>
  14. <script>
  15. var n = 20, // number of layers
  16. m = 200, // number of samples per layer
  17. k = 10; // number of bumps per layer
  18. var stack = d3.stack().keys(d3.range(n)).offset(d3.stackOffsetWiggle),
  19. layers0 = stack(d3.transpose(d3.range(n).map(function() { return bumps(m, k); }))),
  20. layers1 = stack(d3.transpose(d3.range(n).map(function() { return bumps(m, k); }))),
  21. layers = layers0.concat(layers1);
  22. var svg = d3.select("svg"),
  23. width = +svg.attr("width"),
  24. height = +svg.attr("height");
  25. var x = d3.scaleLinear()
  26. .domain([0, m - 1])
  27. .range([0, width]);
  28. var y = d3.scaleLinear()
  29. .domain([d3.min(layers, stackMin), d3.max(layers, stackMax)])
  30. .range([height, 0]);
  31. var z = d3.interpolateCool;
  32. var area = d3.area()
  33. .x(function(d, i) { return x(i); })
  34. .y0(function(d) { return y(d[0]); })
  35. .y1(function(d) { return y(d[1]); });
  36. svg.selectAll("path")
  37. .data(layers0)
  38. .enter().append("path")
  39. .attr("d", area)
  40. .attr("fill", function() { return z(Math.random()); });
  41. function stackMax(layer) {
  42. return d3.max(layer, function(d) { return d[1]; });
  43. }
  44. function stackMin(layer) {
  45. return d3.min(layer, function(d) { return d[0]; });
  46. }
  47. function transition() {
  48. var t;
  49. d3.selectAll("path")
  50. .data((t = layers1, layers1 = layers0, layers0 = t))
  51. .transition()
  52. .duration(2500)
  53. .attr("d", area);
  54. }
  55. // Inspired by Lee Byron’s test data generator.
  56. function bumps(n, m) {
  57. var a = [], i;
  58. for (i = 0; i < n; ++i) a[i] = 0;
  59. for (i = 0; i < m; ++i) bump(a, n);
  60. return a;
  61. }
  62. function bump(a, n) {
  63. var x = 1 / (0.1 + Math.random()),
  64. y = 2 * Math.random() - 0.5,
  65. z = 10 / (0.1 + Math.random());
  66. for (var i = 0; i < n; i++) {
  67. var w = (i / n - y) * z;
  68. a[i] += x * Math.exp(-w * w);
  69. }
  70. }
  71. </script>