nv.d3.multiBarWithBrushChart.js 19 KB

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