Guest User

Untitled

a guest
Oct 16th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. <button type="button" onclick="createPie()">Click Me First!</button>
  2. <button type="button" onclick="updatePie()">Update Diagram!</button>
  3. <div class='foo'></div>
  4.  
  5.  
  6. const chart = {};
  7. const duration = 750;
  8. const width = 160;
  9. const height = 160;
  10.  
  11. const min = Math.min(width, height);
  12. const oRadius = min / 2 * 0.9;
  13. const iRadius = min / 2.5 * 0.85;
  14.  
  15. const pie = d3
  16. .pie()
  17. .value(function(d) {
  18. return d.value;
  19. })
  20. .sort(null);
  21.  
  22. const arc = d3
  23. .arc()
  24. .outerRadius(oRadius)
  25. .innerRadius(iRadius);
  26.  
  27. function arcTween(a) {
  28. const i = d3.interpolate(this._current, a);
  29. this._current = i(0);
  30. return function(t) {
  31. return arc(i(t));
  32. };
  33. };
  34.  
  35. const labels = ['1', '2', '3', '4'];
  36. const color = ["rgba(126,211,33,1)", "rgba(39,173,232,1)", "rgba(229,5,1,1)", "rgba(245,166,35,1)"];
  37.  
  38. const scale = d3.scaleOrdinal()
  39. .domain(labels)
  40. .range(color);
  41.  
  42. const create = function(data) {
  43. const svg = d3
  44. .select('.foo')
  45. .append('svg')
  46. .attr('class', 'pie')
  47. .attr('width', width)
  48. .attr('height', height)
  49. .attr('id', 'svgClass');
  50.  
  51. svg
  52. .append('g')
  53. .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
  54. .attr('id', 'bar');
  55.  
  56. draw(data);
  57. }
  58.  
  59. const draw = function(data) {
  60. const path = d3.select('#bar')
  61. .selectAll('path')
  62. .data(pie(data))
  63.  
  64. path
  65. .enter()
  66. .append('g')
  67. .append('path')
  68. .attr('d', arc)
  69. .attr('fill', (d, i) => {
  70. return scale(d.data.name)
  71. });
  72.  
  73. path
  74. .transition()
  75. .duration(duration)
  76. .attrTween('d', function(d) {
  77. const interpolate = d3.interpolate({
  78. startAngle: 0,
  79. endAngle: 0
  80. }, d);
  81. return function(t) {
  82. return arc(interpolate(t));
  83. };
  84. });
  85. };
  86.  
  87. const data = [{
  88. "name": "1",
  89. "value": 2
  90. }, {
  91. "name": "2",
  92. "value": 1
  93. }, {
  94. "name": "3",
  95. "value": 2
  96. }, {
  97. "name": "4",
  98. "value": 1
  99. }];
  100.  
  101. const newData = [{
  102. "name": "1",
  103. "value": 2
  104. }, {
  105. "name": "2",
  106. "value": 1
  107. }, {
  108. "name": "3",
  109. "value": 2
  110. }];
  111.  
  112. function createPie() {
  113. create(data)
  114. }
  115.  
  116. function updatePie() {
  117. draw(newData)
  118. }
Add Comment
Please, Sign In to add comment