group-stack.html 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <html>
  2. <head>
  3. <title>Group Stacked Bar Chart</title>
  4. <script type="text/javascript" src="../../protovis-d3.2.js"></script>
  5. <script type="text/javascript" src="headcount.js"></script>
  6. </head>
  7. <body>
  8. <script type="text/javascript+protovis">
  9. /* Extract the unique dates, departments and types. */
  10. var dates = pv.uniq(headcount, function(d) d.date),
  11. depts = pv.uniq(headcount, function(d) d.dept),
  12. types = pv.uniq(headcount, function(d) d.type);
  13. /* Build a map of headcounts by date > dept > type. */
  14. var count = pv.nest(headcount)
  15. .key(function(d) d.date)
  16. .key(function(d) d.dept)
  17. .key(function(d) d.type)
  18. .rollup(function(v) v[0].headcount);
  19. /* Compute the maximum stack height using sum(types | date + dept). */
  20. var max = pv.max(dates,
  21. function(q) pv.max(depts,
  22. function(d) pv.sum(types,
  23. function(t) count[q][d][t])));
  24. var w = 250,
  25. h = 400,
  26. x1 = pv.Scale.ordinal(dates).splitBanded(0, w, .8),
  27. x2 = pv.Scale.ordinal(depts).splitBanded(0, x1.range().band, .9),
  28. y = pv.Scale.linear(0, max).range(0, h);
  29. var vis = new pv.Panel()
  30. .width(w)
  31. .height(h)
  32. .bottom(20)
  33. .left(25)
  34. .right(5)
  35. .top(5);
  36. var bar = vis.add(pv.Panel)
  37. .data(dates)
  38. .left(x1)
  39. .add(pv.Layout.Stack)
  40. .layers(types)
  41. .values(depts)
  42. .x(x2)
  43. .y(function(d, t, q) y(count[q][d][t]))
  44. .layer.add(pv.Bar)
  45. .width(x2.range().band)
  46. .title(function(d, t, q) d + "-" + t + ": " + count[q][d][t])
  47. .fillStyle(pv.Colors.category20().by(function(d, t) d + t));
  48. vis.add(pv.Label)
  49. .data(dates)
  50. .bottom(0)
  51. .left(function(d) x1(d) + x1.range().band / 2)
  52. .textMargin(5)
  53. .textBaseline("top")
  54. .textAlign("center")
  55. .text(pv.Format.date("%m/%y"));
  56. vis.add(pv.Rule)
  57. .data(y.ticks())
  58. .bottom(y)
  59. .strokeStyle(function(d) d ? "rgba(255, 255, 255, .3)" : "#000")
  60. .add(pv.Rule)
  61. .left(0)
  62. .width(5)
  63. .strokeStyle("#000")
  64. .anchor("left").add(pv.Label)
  65. .text(y.tickFormat);
  66. vis.render();
  67. </script>
  68. </body>
  69. </html>