nv.d3.growingMultiBarChart.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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.growingMultiBarChart = function() {
  17. "use strict";
  18. //============================================================
  19. // Public Variables with Default Settings
  20. //------------------------------------------------------------
  21. var multibar = nv.models.growingMultiBar()
  22. , xAxis = nv.models.axis()
  23. , yAxis = nv.models.axis()
  24. , legend = nv.models.legend()
  25. , controls = nv.models.legend()
  26. ;
  27. var margin = {top: 30, right: 20, bottom: 50, left: 60}
  28. , width = null
  29. , height = null
  30. , color = nv.utils.defaultColor()
  31. , showControls = true
  32. , showLegend = true
  33. , showXAxis = true
  34. , showYAxis = true
  35. , rightAlignYAxis = false
  36. , reduceXTicks = true // if false a tick will show for every data point
  37. , staggerLabels = false
  38. , rotateLabels = 0
  39. , tooltips = true
  40. , tooltip = function(key, x, y, e, graph) {
  41. return '<h3>' + key + '</h3>' +
  42. '<p>' + y + ' on ' + x + '</p>'
  43. }
  44. , x //can be accessed via chart.xScale()
  45. , y //can be accessed via chart.yScale()
  46. , state = { stacked: false }
  47. , defaultState = null
  48. , noData = "No Data Available."
  49. , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
  50. , controlWidth = function() { return showControls ? 180 : 0 }
  51. , transitionDuration = 250
  52. , selectBars = null
  53. ;
  54. multibar
  55. .stacked(false)
  56. ;
  57. xAxis
  58. .orient('bottom')
  59. .tickPadding(7)
  60. .highlightZero(true)
  61. .showMaxMin(false)
  62. .tickFormat(function(d) { return d })
  63. ;
  64. yAxis
  65. .orient((rightAlignYAxis) ? 'right' : 'left')
  66. .tickFormat(d3.format(',.1f'))
  67. ;
  68. controls.updateState(false);
  69. //============================================================
  70. //============================================================
  71. // Private Variables
  72. //------------------------------------------------------------
  73. var showTooltip = function(e, offsetElement) {
  74. var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
  75. top = e.pos[1] + ( offsetElement.offsetTop || 0),
  76. x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)),
  77. y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)),
  78. content = tooltip(e.series.key, x, y, e, chart);
  79. nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
  80. };
  81. //============================================================
  82. function chart(selection) {
  83. selection.each(function(data) {
  84. var container = d3.select(this),
  85. that = this;
  86. var availableWidth = (width || parseInt(container.style('width')) || 960)
  87. - margin.left - margin.right,
  88. availableHeight = (height || parseInt(container.style('height')) || 400)
  89. - margin.top - margin.bottom;
  90. chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
  91. chart.container = this;
  92. //set state.disabled
  93. state.disabled = data.map(function(d) { return !!d.disabled });
  94. if (!defaultState) {
  95. var key;
  96. defaultState = {};
  97. for (key in state) {
  98. if (state[key] instanceof Array)
  99. defaultState[key] = state[key].slice(0);
  100. else
  101. defaultState[key] = state[key];
  102. }
  103. }
  104. //------------------------------------------------------------
  105. // Display noData message if there's nothing to show.
  106. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
  107. var noDataText = container.selectAll('.nv-noData').data([noData]);
  108. noDataText.enter().append('text')
  109. .attr('class', 'nvd3 nv-noData')
  110. .attr('dy', '-.7em')
  111. .style('text-anchor', 'middle');
  112. noDataText
  113. .attr('x', margin.left + availableWidth / 2)
  114. .attr('y', margin.top + availableHeight / 2)
  115. .text(function(d) { return d });
  116. return chart;
  117. } else {
  118. container.selectAll('.nv-noData').remove();
  119. }
  120. //------------------------------------------------------------
  121. //------------------------------------------------------------
  122. // Setup Scales
  123. x = multibar.xScale();
  124. y = multibar.yScale();
  125. //------------------------------------------------------------
  126. //------------------------------------------------------------
  127. // Setup containers and skeleton of chart
  128. var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]);
  129. var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g');
  130. var g = wrap.select('g');
  131. gEnter.append('g').attr('class', 'nv-x nv-axis');
  132. gEnter.append('g').attr('class', 'nv-y nv-axis');
  133. gEnter.append('g').attr('class', 'nv-barsWrap');
  134. gEnter.append('g').attr('class', 'nv-legendWrap');
  135. gEnter.append('g').attr('class', 'nv-controlsWrap');
  136. //------------------------------------------------------------
  137. //------------------------------------------------------------
  138. // Legend
  139. if (showLegend) {
  140. legend.width(availableWidth - controlWidth());
  141. if (multibar.barColor())
  142. data.forEach(function(series,i) {
  143. series.color = d3.rgb('#ccc').darker(i * 1.5).toString();
  144. })
  145. g.select('.nv-legendWrap')
  146. .datum(data)
  147. .call(legend);
  148. if ( margin.top != legend.height()) {
  149. margin.top = legend.height();
  150. availableHeight = (height || parseInt(container.style('height')) || 400)
  151. - margin.top - margin.bottom;
  152. }
  153. g.select('.nv-legendWrap')
  154. .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
  155. }
  156. //------------------------------------------------------------
  157. //------------------------------------------------------------
  158. // Controls
  159. if (showControls) {
  160. var controlsData = [
  161. { key: 'Grouped', disabled: multibar.stacked() },
  162. { key: 'Stacked', disabled: !multibar.stacked() }
  163. ];
  164. controls.width(controlWidth()).color(['#444', '#444', '#444']);
  165. g.select('.nv-controlsWrap')
  166. .datum(controlsData)
  167. .attr('transform', 'translate(0,' + (-margin.top) +')')
  168. .call(controls);
  169. }
  170. //------------------------------------------------------------
  171. wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
  172. if (rightAlignYAxis) {
  173. g.select(".nv-y.nv-axis")
  174. .attr("transform", "translate(" + availableWidth + ",0)");
  175. }
  176. //------------------------------------------------------------
  177. // Main Chart Component(s)
  178. multibar
  179. .disabled(data.map(function(series) { return series.disabled }))
  180. .width(availableWidth)
  181. .height(availableHeight)
  182. .color(data.map(function(d,i) {
  183. return d.color || color(d, i);
  184. }).filter(function(d,i) { return !data[i].disabled }))
  185. selectBars = multibar.selectBars;
  186. var barsWrap = g.select('.nv-barsWrap')
  187. .datum(data.filter(function(d) { return !d.disabled }))
  188. barsWrap.transition().call(multibar);
  189. //------------------------------------------------------------
  190. //------------------------------------------------------------
  191. // Setup Axes
  192. if (showXAxis) {
  193. xAxis
  194. .scale(x)
  195. .ticks( availableWidth / 100 )
  196. .tickSize(-availableHeight, 0);
  197. g.select('.nv-x.nv-axis')
  198. .attr('transform', 'translate(0,' + y.range()[0] + ')');
  199. g.select('.nv-x.nv-axis').transition()
  200. .call(xAxis);
  201. var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g');
  202. xTicks
  203. .selectAll('line, text')
  204. .style('opacity', 1)
  205. if (staggerLabels) {
  206. var getTranslate = function(x,y) {
  207. return "translate(" + x + "," + y + ")";
  208. };
  209. var staggerUp = 5, staggerDown = 17; //pixels to stagger by
  210. // Issue #140
  211. xTicks
  212. .selectAll("text")
  213. .attr('transform', function(d,i,j) {
  214. return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown));
  215. });
  216. var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;
  217. g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text")
  218. .attr("transform", function(d,i) {
  219. return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp);
  220. });
  221. }
  222. if (reduceXTicks)
  223. xTicks
  224. .filter(function(d,i) {
  225. return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0;
  226. })
  227. .selectAll('text, line')
  228. .style('opacity', 0);
  229. if(rotateLabels)
  230. xTicks
  231. .selectAll('.tick text')
  232. .attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
  233. .style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
  234. g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text')
  235. .style('opacity', 1);
  236. }
  237. if (showYAxis) {
  238. yAxis
  239. .scale(y)
  240. .ticks( availableHeight / 36 )
  241. .tickSize( -availableWidth, 0);
  242. g.select('.nv-y.nv-axis').transition()
  243. .call(yAxis);
  244. }
  245. //------------------------------------------------------------
  246. //============================================================
  247. // Event Handling/Dispatching (in chart's scope)
  248. //------------------------------------------------------------
  249. legend.dispatch.on('stateChange', function(newState) {
  250. state = newState;
  251. dispatch.stateChange(state);
  252. chart.update();
  253. });
  254. controls.dispatch.on('legendClick', function(d,i) {
  255. if (!d.disabled) return;
  256. controlsData = controlsData.map(function(s) {
  257. s.disabled = true;
  258. return s;
  259. });
  260. d.disabled = false;
  261. switch (d.key) {
  262. case 'Grouped':
  263. multibar.stacked(false);
  264. break;
  265. case 'Stacked':
  266. multibar.stacked(true);
  267. break;
  268. }
  269. state.stacked = multibar.stacked();
  270. dispatch.stateChange(state);
  271. chart.update();
  272. });
  273. dispatch.on('tooltipShow', function(e) {
  274. if (tooltips) showTooltip(e, that.parentNode)
  275. });
  276. // Update chart from a state object passed to event handler
  277. dispatch.on('changeState', function(e) {
  278. if (typeof e.disabled !== 'undefined') {
  279. data.forEach(function(series,i) {
  280. series.disabled = e.disabled[i];
  281. });
  282. state.disabled = e.disabled;
  283. }
  284. if (typeof e.stacked !== 'undefined') {
  285. multibar.stacked(e.stacked);
  286. state.stacked = e.stacked;
  287. }
  288. chart.update();
  289. });
  290. //============================================================
  291. });
  292. return chart;
  293. }
  294. //============================================================
  295. // Event Handling/Dispatching (out of chart's scope)
  296. //------------------------------------------------------------
  297. multibar.dispatch.on('elementMouseover.tooltip', function(e) {
  298. e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
  299. dispatch.tooltipShow(e);
  300. });
  301. multibar.dispatch.on('elementMouseout.tooltip', function(e) {
  302. dispatch.tooltipHide(e);
  303. });
  304. dispatch.on('tooltipHide', function() {
  305. if (tooltips) nv.tooltip.cleanup();
  306. });
  307. //============================================================
  308. //============================================================
  309. // Expose Public Variables
  310. //------------------------------------------------------------
  311. // expose chart's sub-components
  312. chart.dispatch = dispatch;
  313. chart.multibar = multibar;
  314. chart.legend = legend;
  315. chart.xAxis = xAxis;
  316. chart.yAxis = yAxis;
  317. d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'clipEdge',
  318. 'id', 'stacked', 'stackOffset', 'delay', 'barColor','groupSpacing');
  319. chart.options = nv.utils.optionsFunc.bind(chart);
  320. chart.margin = function(_) {
  321. if (!arguments.length) return margin;
  322. margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
  323. margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
  324. margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
  325. margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
  326. return chart;
  327. };
  328. chart.width = function(_) {
  329. if (!arguments.length) return width;
  330. width = _;
  331. return chart;
  332. };
  333. chart.height = function(_) {
  334. if (!arguments.length) return height;
  335. height = _;
  336. return chart;
  337. };
  338. chart.color = function(_) {
  339. if (!arguments.length) return color;
  340. color = nv.utils.getColor(_);
  341. legend.color(color);
  342. return chart;
  343. };
  344. chart.showControls = function(_) {
  345. if (!arguments.length) return showControls;
  346. showControls = _;
  347. return chart;
  348. };
  349. chart.showLegend = function(_) {
  350. if (!arguments.length) return showLegend;
  351. showLegend = _;
  352. return chart;
  353. };
  354. chart.showXAxis = function(_) {
  355. if (!arguments.length) return showXAxis;
  356. showXAxis = _;
  357. return chart;
  358. };
  359. chart.showYAxis = function(_) {
  360. if (!arguments.length) return showYAxis;
  361. showYAxis = _;
  362. return chart;
  363. };
  364. chart.rightAlignYAxis = function(_) {
  365. if(!arguments.length) return rightAlignYAxis;
  366. rightAlignYAxis = _;
  367. yAxis.orient( (_) ? 'right' : 'left');
  368. return chart;
  369. };
  370. chart.reduceXTicks= function(_) {
  371. if (!arguments.length) return reduceXTicks;
  372. reduceXTicks = _;
  373. return chart;
  374. };
  375. chart.rotateLabels = function(_) {
  376. if (!arguments.length) return rotateLabels;
  377. rotateLabels = _;
  378. return chart;
  379. }
  380. chart.staggerLabels = function(_) {
  381. if (!arguments.length) return staggerLabels;
  382. staggerLabels = _;
  383. return chart;
  384. };
  385. chart.tooltip = function(_) {
  386. if (!arguments.length) return tooltip;
  387. tooltip = _;
  388. return chart;
  389. };
  390. chart.tooltips = function(_) {
  391. if (!arguments.length) return tooltips;
  392. tooltips = _;
  393. return chart;
  394. };
  395. chart.tooltipContent = function(_) {
  396. if (!arguments.length) return tooltip;
  397. tooltip = _;
  398. return chart;
  399. };
  400. chart.state = function(_) {
  401. if (!arguments.length) return state;
  402. state = _;
  403. return chart;
  404. };
  405. chart.defaultState = function(_) {
  406. if (!arguments.length) return defaultState;
  407. defaultState = _;
  408. return chart;
  409. };
  410. chart.noData = function(_) {
  411. if (!arguments.length) return noData;
  412. noData = _;
  413. return chart;
  414. };
  415. chart.transitionDuration = function(_) {
  416. if (!arguments.length) return transitionDuration;
  417. transitionDuration = _;
  418. return chart;
  419. };
  420. chart.selectBars = function(args) {
  421. if (!arguments.length) return selectBars;
  422. selectBars(args);
  423. return chart;
  424. };
  425. //============================================================
  426. return chart;
  427. }