nv.d3.multiBarWithBrushChart.js 20 KB

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