nv.d3.growingPie.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. var group = d3.select(this);
  169. group
  170. .attr('transform', function(d) {
  171. if (labelSunbeamLayout) {
  172. d.outerRadius = arcRadius + 10; // Set Outer Coordinate
  173. d.innerRadius = arcRadius + 15; // Set Inner Coordinate
  174. var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
  175. if ((d.startAngle+d.endAngle)/2 < Math.PI) {
  176. rotateAngle -= 90;
  177. } else {
  178. rotateAngle += 90;
  179. }
  180. return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
  181. } else {
  182. d.outerRadius = radius + 10; // Set Outer Coordinate
  183. d.innerRadius = radius + 15; // Set Inner Coordinate
  184. return 'translate(' + labelsArc.centroid(d) + ')'
  185. }
  186. });
  187. group.append('rect')
  188. .style('stroke', '#fff')
  189. .style('fill', '#fff')
  190. .attr("rx", 3)
  191. .attr("ry", 3);
  192. group.append('text')
  193. .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
  194. .style('fill', '#000')
  195. });
  196. var labelLocationHash = {};
  197. var avgHeight = 14;
  198. var avgWidth = 140;
  199. var createHashKey = function(coordinates) {
  200. return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight;
  201. };
  202. pieLabels.transition()
  203. .attr('transform', function(d) {
  204. if (labelSunbeamLayout) {
  205. d.outerRadius = arcRadius + 10; // Set Outer Coordinate
  206. d.innerRadius = arcRadius + 15; // Set Inner Coordinate
  207. var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI);
  208. if ((d.startAngle+d.endAngle)/2 < Math.PI) {
  209. rotateAngle -= 90;
  210. } else {
  211. rotateAngle += 90;
  212. }
  213. return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')';
  214. } else {
  215. d.outerRadius = radius + 10; // Set Outer Coordinate
  216. d.innerRadius = radius + 15; // Set Inner Coordinate
  217. /*
  218. Overlapping pie labels are not good. What this attempts to do is, prevent overlapping.
  219. Each label location is hashed, and if a hash collision occurs, we assume an overlap.
  220. Adjust the label's y-position to remove the overlap.
  221. */
  222. var center = labelsArc.centroid(d);
  223. var hashKey = createHashKey(center);
  224. if (labelLocationHash[hashKey]) {
  225. center[1] -= avgHeight;
  226. }
  227. labelLocationHash[createHashKey(center)] = true;
  228. return 'translate(' + center + ')'
  229. }
  230. });
  231. pieLabels.select(".nv-label text")
  232. .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
  233. .text(function(d, i) {
  234. var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
  235. var labelTypes = {
  236. "key" : getX(d.data),
  237. "value": getY(d.data),
  238. "percent": d3.format('%')(percent)
  239. };
  240. return (d.value && percent > labelThreshold) ? labelTypes[labelType] : '';
  241. });
  242. }
  243. // Computes the angle of an arc, converting from radians to degrees.
  244. function angle(d) {
  245. var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
  246. return a > 90 ? a - 180 : a;
  247. }
  248. function arcTween(a) {
  249. a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle;
  250. a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle;
  251. if (!donut) a.innerRadius = 0;
  252. var i = d3.interpolate(this._current, a);
  253. this._current = i(0);
  254. return function(t) {
  255. return arc(i(t));
  256. };
  257. }
  258. function tweenPie(b) {
  259. b.innerRadius = 0;
  260. var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
  261. return function(t) {
  262. return arc(i(t));
  263. };
  264. }
  265. });
  266. return chart;
  267. }
  268. //============================================================
  269. // Expose Public Variables
  270. //------------------------------------------------------------
  271. chart.dispatch = dispatch;
  272. chart.options = nv.utils.optionsFunc.bind(chart);
  273. chart.margin = function(_) {
  274. if (!arguments.length) return margin;
  275. margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
  276. margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
  277. margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
  278. margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
  279. return chart;
  280. };
  281. chart.width = function(_) {
  282. if (!arguments.length) return width;
  283. width = _;
  284. return chart;
  285. };
  286. chart.height = function(_) {
  287. if (!arguments.length) return height;
  288. height = _;
  289. return chart;
  290. };
  291. chart.values = function(_) {
  292. nv.log("pie.values() is no longer supported.");
  293. return chart;
  294. };
  295. chart.x = function(_) {
  296. if (!arguments.length) return getX;
  297. getX = _;
  298. return chart;
  299. };
  300. chart.y = function(_) {
  301. if (!arguments.length) return getY;
  302. getY = d3.functor(_);
  303. return chart;
  304. };
  305. chart.description = function(_) {
  306. if (!arguments.length) return getDescription;
  307. getDescription = _;
  308. return chart;
  309. };
  310. chart.showLabels = function(_) {
  311. if (!arguments.length) return showLabels;
  312. showLabels = _;
  313. return chart;
  314. };
  315. chart.labelSunbeamLayout = function(_) {
  316. if (!arguments.length) return labelSunbeamLayout;
  317. labelSunbeamLayout = _;
  318. return chart;
  319. };
  320. chart.donutLabelsOutside = function(_) {
  321. if (!arguments.length) return donutLabelsOutside;
  322. donutLabelsOutside = _;
  323. return chart;
  324. };
  325. chart.pieLabelsOutside = function(_) {
  326. if (!arguments.length) return pieLabelsOutside;
  327. pieLabelsOutside = _;
  328. return chart;
  329. };
  330. chart.labelType = function(_) {
  331. if (!arguments.length) return labelType;
  332. labelType = _;
  333. labelType = labelType || "key";
  334. return chart;
  335. };
  336. chart.donut = function(_) {
  337. if (!arguments.length) return donut;
  338. donut = _;
  339. return chart;
  340. };
  341. chart.donutRatio = function(_) {
  342. if (!arguments.length) return donutRatio;
  343. donutRatio = _;
  344. return chart;
  345. };
  346. chart.startAngle = function(_) {
  347. if (!arguments.length) return startAngle;
  348. startAngle = _;
  349. return chart;
  350. };
  351. chart.endAngle = function(_) {
  352. if (!arguments.length) return endAngle;
  353. endAngle = _;
  354. return chart;
  355. };
  356. chart.id = function(_) {
  357. if (!arguments.length) return id;
  358. id = _;
  359. return chart;
  360. };
  361. chart.color = function(_) {
  362. if (!arguments.length) return color;
  363. color = nv.utils.getColor(_);
  364. return chart;
  365. };
  366. chart.valueFormat = function(_) {
  367. if (!arguments.length) return valueFormat;
  368. valueFormat = _;
  369. return chart;
  370. };
  371. chart.labelThreshold = function(_) {
  372. if (!arguments.length) return labelThreshold;
  373. labelThreshold = _;
  374. return chart;
  375. };
  376. chart.selectSlices = function(args) {
  377. if (!arguments.length) return selectSlices;
  378. selectSlices(args);
  379. return chart;
  380. };
  381. //============================================================
  382. return chart;
  383. }