nv.d3.growingPie.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. nv.models.growingPie = function() {
  17. "use strict";
  18. //============================================================
  19. // Public Variables with Default Settings
  20. //------------------------------------------------------------
  21. var margin = {top: 0, right: 0, bottom: 0, left: 0}
  22. , width = 500
  23. , height = 500
  24. , getX = function(d) { return d.x }
  25. , getY = function(d) { return d.y }
  26. , getDescription = function(d) { return d.description }
  27. , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
  28. , color = nv.utils.defaultColor()
  29. , valueFormat = d3.format(',.2f')
  30. , showLabels = true
  31. , pieLabelsOutside = true
  32. , donutLabelsOutside = false
  33. , labelType = "key"
  34. , labelThreshold = .02 //if slice percentage is under this, don't show label
  35. , donut = false
  36. , labelSunbeamLayout = false
  37. , startAngle = false
  38. , endAngle = false
  39. , donutRatio = 0.5
  40. , selectSlices = null
  41. , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
  42. ;
  43. //============================================================
  44. function chart(selection) {
  45. selection.each(function(data) {
  46. var availableWidth = width - margin.left - margin.right,
  47. availableHeight = height - margin.top - margin.bottom,
  48. radius = Math.min(availableWidth, availableHeight) / 2,
  49. arcRadius = radius-(radius / 5),
  50. container = d3.select(this);
  51. //------------------------------------------------------------
  52. // Setup containers and skeleton of chart
  53. //var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]);
  54. var wrap = container.selectAll('.nv-wrap.nv-pie').data(data);
  55. var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id);
  56. var gEnter = wrapEnter.append('g');
  57. var g = wrap.select('g');
  58. gEnter.append('g').attr('class', 'nv-pie');
  59. gEnter.append('g').attr('class', 'nv-pieLabels');
  60. wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
  61. g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
  62. g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')');
  63. //------------------------------------------------------------
  64. container
  65. .on('click', function(d,i) {
  66. dispatch.chartClick({
  67. data: d,
  68. index: i,
  69. pos: d3.event,
  70. id: id
  71. });
  72. });
  73. var arc = d3.svg.arc()
  74. .outerRadius(arcRadius);
  75. var arcOver = d3.svg.arc()
  76. .outerRadius(arcRadius + 10);
  77. if (startAngle) arc.startAngle(startAngle)
  78. if (endAngle) arc.endAngle(endAngle);
  79. if (donut) arc.innerRadius(radius * donutRatio);
  80. // Setup the Pie chart and choose the data element
  81. var pie = d3.layout.pie()
  82. .sort(null)
  83. .value(function(d) { return d.disabled ? 0 : getY(d) });
  84. var slices = wrap.select('.nv-pie').selectAll('.nv-slice')
  85. .data(pie);
  86. var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label')
  87. .data(pie);
  88. slices.exit().remove();
  89. pieLabels.exit().remove();
  90. selectSlices = function(selected) {
  91. $(selected).each(function(cnt, item){
  92. slices.each(function(d, i) {
  93. if ((typeof d.data.obj.from != "undefined" && d.data.obj.from == item) || d.data.obj.value == item) {
  94. d3.select(this).classed('selected', true);
  95. d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
  96. }
  97. });
  98. });
  99. };
  100. var ae = slices.enter().append('g')
  101. .attr('class', 'nv-slice')
  102. .on('mouseover', function(d,i){
  103. d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
  104. d3.select(this).classed('hover', true);
  105. dispatch.elementMouseover({
  106. label: getX(d.data),
  107. value: getY(d.data),
  108. point: d.data,
  109. pointIndex: i,
  110. pos: [d3.event.pageX, d3.event.pageY],
  111. id: id
  112. });
  113. })
  114. .on('mouseout', function(d,i){
  115. if (!d3.select(this).classed('selected')){
  116. d3.select(this).select("path").transition().duration(100).attr("d", arc);
  117. }
  118. d3.select(this).classed('hover', false);
  119. dispatch.elementMouseout({
  120. label: getX(d.data),
  121. value: getY(d.data),
  122. point: d.data,
  123. index: i,
  124. id: id
  125. });
  126. })
  127. .on('click', function(d,i) {
  128. d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
  129. dispatch.elementClick({
  130. label: getX(d.data),
  131. value: getY(d.data),
  132. point: d.data,
  133. index: i,
  134. pos: d3.event,
  135. id: id
  136. });
  137. d3.event.stopPropagation();
  138. })
  139. .on('dblclick', function(d,i) {
  140. d3.select(this).select("path").transition().duration(100).attr("d", arc);
  141. dispatch.elementDblClick({
  142. label: getX(d.data),
  143. value: getY(d.data),
  144. point: d.data,
  145. index: i,
  146. pos: d3.event,
  147. id: id
  148. });
  149. d3.event.stopPropagation();
  150. });
  151. slices
  152. .attr('fill', function(d,i) { return color(d, i); })
  153. .attr('stroke', function(d,i) { return color(d, i); });
  154. var paths = ae.append('path')
  155. .each(function(d) { this._current = d; });
  156. //.attr('d', arc);
  157. slices.select('path')
  158. .transition()
  159. .attr('d', arc)
  160. .attrTween('d', arcTween);
  161. if (showLabels) {
  162. // This does the normal label
  163. var labelsArc = d3.svg.arc().innerRadius(0);
  164. if (pieLabelsOutside){ labelsArc = arc; }
  165. if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); }
  166. pieLabels.enter().append("g").classed("nv-label",true)
  167. .each(function(d,i) {
  168. if (d.value > 0) {
  169. var group = d3.select(this);
  170. group
  171. .attr('transform', function(d) {
  172. if (labelSunbeamLayout) {
  173. d.outerRadius = arcRadius + 10; // Set Outer Coordinate
  174. d.innerRadius = arcRadius + 15; // Set Inner Coordinate
  175. var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
  176. if ((d.startAngle+d.endAngle)/2 < Math.PI) {
  177. rotateAngle -= 90;
  178. } else {
  179. rotateAngle += 90;
  180. }
  181. return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
  182. } else {
  183. d.outerRadius = radius + 10; // Set Outer Coordinate
  184. d.innerRadius = radius + 15; // Set Inner Coordinate
  185. return 'translate(' + labelsArc.centroid(d) + ')'
  186. }
  187. });
  188. group.append('rect')
  189. .style('stroke', '#fff')
  190. .style('fill', '#fff')
  191. .attr("rx", 3)
  192. .attr("ry", 3);
  193. group.append('text')
  194. .style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned
  195. .style('fill', '#000')
  196. }
  197. });
  198. var labelLocationHash = {};
  199. var avgHeight = 14;
  200. var avgWidth = 140;
  201. var createHashKey = function(coordinates) {
  202. return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
  203. };
  204. pieLabels.transition()
  205. .attr('transform', function(d) {
  206. if (d.value > 0) {
  207. if (labelSunbeamLayout) {
  208. d.outerRadius = arcRadius + 10; // Set Outer Coordinate
  209. d.innerRadius = arcRadius + 15; // Set Inner Coordinate
  210. var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
  211. if ((d.startAngle+d.endAngle)/2 < Math.PI) {
  212. rotateAngle -= 90;
  213. } else {
  214. rotateAngle += 90;
  215. }
  216. return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
  217. } else {
  218. d.outerRadius = radius + 10; // Set Outer Coordinate
  219. d.innerRadius = radius + 15; // Set Inner Coordinate
  220. /*
  221. Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
  222. Each label location is hashed, and if a hash collision occurs, we assume an overlap.
  223. Adjust the label's y-position to remove the overlap.
  224. */
  225. var center = labelsArc.centroid(d);
  226. var hashKey = createHashKey(center);
  227. if (labelLocationHash[hashKey]) {
  228. center[1] -= avgHeight;
  229. }
  230. labelLocationHash[createHashKey(center)] = true;
  231. return 'translate(' + center + ')'
  232. }
  233. }
  234. });
  235. pieLabels.select(".nv-label text")
  236. .style('text-anchor', function(d){
  237. if (d.value > 0) {
  238. if (labelSunbeamLayout) {
  239. return ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end'); //center the text on it's origin or begin/end if orthogonal aligned
  240. }
  241. else {
  242. return 'middle';
  243. }
  244. }
  245. })
  246. .text(function(d, i) {
  247. if (d.value > 0) {
  248. var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
  249. var labelTypes = {
  250. "key": getX(d.data),
  251. "value": getY(d.data),
  252. "percent": d3.format('%')(percent)
  253. };
  254. return (d.value && percent > labelThreshold) ? labelTypes[labelType] : '';
  255. }
  256. else {
  257. return '';
  258. }
  259. });
  260. }
  261. // Computes the angle of an arc, converting from radians to degrees.
  262. function angle(d) {
  263. var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
  264. return a > 90 ? a - 180 : a;
  265. }
  266. function arcTween(a) {
  267. a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
  268. a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
  269. if (!donut) a.innerRadius = 0;
  270. var i = d3.interpolate(this._current, a);
  271. this._current = i(0);
  272. return function(t) {
  273. return arc(i(t));
  274. };
  275. }
  276. function tweenPie(b) {
  277. b.innerRadius = 0;
  278. var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
  279. return function(t) {
  280. return arc(i(t));
  281. };
  282. }
  283. });
  284. return chart;
  285. }
  286. //============================================================
  287. // Expose Public Variables
  288. //------------------------------------------------------------
  289. chart.dispatch = dispatch;
  290. chart.options = nv.utils.optionsFunc.bind(chart);
  291. chart.margin = function(_) {
  292. if (!arguments.length) return margin;
  293. margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
  294. margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
  295. margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
  296. margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
  297. return chart;
  298. };
  299. chart.width = function(_) {
  300. if (!arguments.length) return width;
  301. width = _;
  302. return chart;
  303. };
  304. chart.height = function(_) {
  305. if (!arguments.length) return height;
  306. height = _;
  307. return chart;
  308. };
  309. chart.values = function(_) {
  310. nv.log("pie.values() is no longer supported.");
  311. return chart;
  312. };
  313. chart.x = function(_) {
  314. if (!arguments.length) return getX;
  315. getX = _;
  316. return chart;
  317. };
  318. chart.y = function(_) {
  319. if (!arguments.length) return getY;
  320. getY = d3.functor(_);
  321. return chart;
  322. };
  323. chart.description = function(_) {
  324. if (!arguments.length) return getDescription;
  325. getDescription = _;
  326. return chart;
  327. };
  328. chart.showLabels = function(_) {
  329. if (!arguments.length) return showLabels;
  330. showLabels = _;
  331. return chart;
  332. };
  333. chart.labelSunbeamLayout = function(_) {
  334. if (!arguments.length) return labelSunbeamLayout;
  335. labelSunbeamLayout = _;
  336. return chart;
  337. };
  338. chart.donutLabelsOutside = function(_) {
  339. if (!arguments.length) return donutLabelsOutside;
  340. donutLabelsOutside = _;
  341. return chart;
  342. };
  343. chart.pieLabelsOutside = function(_) {
  344. if (!arguments.length) return pieLabelsOutside;
  345. pieLabelsOutside = _;
  346. return chart;
  347. };
  348. chart.labelType = function(_) {
  349. if (!arguments.length) return labelType;
  350. labelType = _;
  351. labelType = labelType || "key";
  352. return chart;
  353. };
  354. chart.donut = function(_) {
  355. if (!arguments.length) return donut;
  356. donut = _;
  357. return chart;
  358. };
  359. chart.donutRatio = function(_) {
  360. if (!arguments.length) return donutRatio;
  361. donutRatio = _;
  362. return chart;
  363. };
  364. chart.startAngle = function(_) {
  365. if (!arguments.length) return startAngle;
  366. startAngle = _;
  367. return chart;
  368. };
  369. chart.endAngle = function(_) {
  370. if (!arguments.length) return endAngle;
  371. endAngle = _;
  372. return chart;
  373. };
  374. chart.id = function(_) {
  375. if (!arguments.length) return id;
  376. id = _;
  377. return chart;
  378. };
  379. chart.color = function(_) {
  380. if (!arguments.length) return color;
  381. color = nv.utils.getColor(_);
  382. return chart;
  383. };
  384. chart.valueFormat = function(_) {
  385. if (!arguments.length) return valueFormat;
  386. valueFormat = _;
  387. return chart;
  388. };
  389. chart.labelThreshold = function(_) {
  390. if (!arguments.length) return labelThreshold;
  391. labelThreshold = _;
  392. return chart;
  393. };
  394. chart.selectSlices = function(args) {
  395. if (!arguments.length) return selectSlices;
  396. selectSlices(args);
  397. return chart;
  398. };
  399. //============================================================
  400. return chart;
  401. }