nv.d3.multiBarWithBrushChart.js 20 KB

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