nv.d3.growingMultiBarChart.js 16 KB

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