nv.d3.multiBarWithBrushChart.js 18 KB

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