nv.d3.multiBarWithBrushChart.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. try {
  170. g.select('.nv-legendWrap')
  171. .datum(data)
  172. .call(legend);
  173. }
  174. catch (e){}
  175. if ( margin.top != legend.height()) {
  176. margin.top = legend.height();
  177. availableHeight = (height || parseInt(container.style('height')) || 400)
  178. - margin.top - margin.bottom;
  179. }
  180. g.select('.nv-legendWrap')
  181. .attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')');
  182. }
  183. //------------------------------------------------------------
  184. //------------------------------------------------------------
  185. // Controls
  186. if (showControls) {
  187. var controlsData = [
  188. { key: LABELS.GROUPED, disabled: multibar.stacked() },
  189. { key: LABELS.STACKED, disabled: !multibar.stacked() },
  190. { key: LABELS.SELECT, disabled: !selectionEnabled, checkbox: true }
  191. ];
  192. controls.width(controlWidth()).color(['#444', '#444', '#444']);
  193. g.select('.nv-controlsWrap')
  194. .datum(controlsData)
  195. .attr('transform', 'translate(0,' + (-margin.top) +')')
  196. .call(controls);
  197. }
  198. //------------------------------------------------------------
  199. wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
  200. if (rightAlignYAxis) {
  201. g.select(".nv-y.nv-axis")
  202. .attr("transform", "translate(" + availableWidth + ",0)");
  203. }
  204. //------------------------------------------------------------
  205. // Main Chart Component(s)
  206. multibar
  207. .disabled(data.map(function(series) { return series.disabled }))
  208. .width(availableWidth)
  209. .height(availableHeight)
  210. .color(data.map(function(d,i) {
  211. return d.color || color(d, i);
  212. }).filter(function(d,i) { return !data[i].disabled }))
  213. selectBars = multibar.selectBars;
  214. var dataBars = data.filter(function(d) { return !d.disabled && d.bar });
  215. var barsWrap = g.select('.nv-barsWrap')
  216. .datum(data.filter(function(d) { return !d.disabled }))
  217. barsWrap.transition().call(multibar);
  218. //------------------------------------------------------------
  219. //------------------------------------------------------------
  220. // Setup Brush
  221. if (selectionEnabled){
  222. enableBrush();
  223. }
  224. function enableBrush() {
  225. if (g.selectAll('.nv-brush')[0].length == 0) {
  226. gEnter.append('g').attr('class', 'nv-brushBackground');
  227. gEnter.append('g').attr('class', 'nv-x nv-brush');
  228. brush
  229. .x(x)
  230. .on('brush', onBrush)
  231. .on('brushend', onBrushEnd)
  232. if (brushExtent) brush.extent(brushExtent);
  233. var brushBG = g.select('.nv-brushBackground').selectAll('g')
  234. .data([brushExtent || brush.extent()])
  235. var brushBGenter = brushBG.enter()
  236. .append('g');
  237. brushBGenter.append('rect')
  238. .attr('class', 'left')
  239. .attr('x', 0)
  240. .attr('y', 0)
  241. .attr('height', availableHeight);
  242. brushBGenter.append('rect')
  243. .attr('class', 'right')
  244. .attr('x', 0)
  245. .attr('y', 0)
  246. .attr('height', availableHeight);
  247. var gBrush = g.select('.nv-x.nv-brush')
  248. .call(brush);
  249. gBrush.selectAll('rect')
  250. .attr('height', availableHeight);
  251. }
  252. else {
  253. g.selectAll('.nv-brush').attr('display', 'inline');
  254. }
  255. }
  256. function disableBrush() {
  257. g.selectAll('.nv-brush').attr('display', 'none');
  258. }
  259. //------------------------------------------------------------
  260. // Setup Axes
  261. if (showXAxis) {
  262. xAxis
  263. .scale(x)
  264. .ticks( availableWidth / 100 )
  265. .tickSize(-availableHeight, 0);
  266. g.select('.nv-x.nv-axis')
  267. .attr('transform', 'translate(0,' + y.range()[0] + ')');
  268. g.select('.nv-x.nv-axis').transition()
  269. .call(xAxis);
  270. var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g');
  271. xTicks
  272. .selectAll('line, text')
  273. .style('opacity', 1)
  274. if (staggerLabels) {
  275. var getTranslate = function(x,y) {
  276. return "translate(" + x + "," + y + ")";
  277. };
  278. var staggerUp = 5, staggerDown = 17; //pixels to stagger by
  279. // Issue #140
  280. xTicks
  281. .selectAll("text")
  282. .attr('transform', function(d,i,j) {
  283. return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown));
  284. });
  285. var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length;
  286. g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text")
  287. .attr("transform", function(d,i) {
  288. return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp);
  289. });
  290. }
  291. if (reduceXTicks)
  292. xTicks
  293. .filter(function(d,i) {
  294. return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0;
  295. })
  296. .selectAll('text, line')
  297. .style('opacity', 0);
  298. if(rotateLabels)
  299. xTicks
  300. .selectAll('.tick text')
  301. .attr('transform', 'rotate(' + rotateLabels + ' 0,0)')
  302. .style('text-anchor', rotateLabels > 0 ? 'start' : 'end');
  303. g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text')
  304. .style('opacity', 1);
  305. }
  306. if (showYAxis) {
  307. yAxis
  308. .scale(y)
  309. .ticks( availableHeight / 36 )
  310. .tickSize( -availableWidth, 0);
  311. g.select('.nv-y.nv-axis').transition()
  312. .call(yAxis);
  313. }
  314. //------------------------------------------------------------
  315. //============================================================
  316. // Event Handling/Dispatching (in chart's scope)
  317. //------------------------------------------------------------
  318. legend.dispatch.on('stateChange', function(newState) {
  319. state = newState;
  320. dispatch.stateChange(state);
  321. chart.update();
  322. });
  323. controls.dispatch.on('legendClick', function(d,i) {
  324. if (typeof d.checkbox == "undefined"){
  325. if (!d.disabled) return;
  326. controlsData = controlsData.map(function(s) {
  327. s.disabled = true;
  328. return s;
  329. });
  330. d.disabled = false;
  331. }
  332. switch (d.key) {
  333. case LABELS.GROUPED:
  334. multibar.stacked(false);
  335. break;
  336. case LABELS.STACKED:
  337. multibar.stacked(true);
  338. break;
  339. case LABELS.SELECT:
  340. selectionEnabled = !selectionEnabled;
  341. break;
  342. }
  343. state.stacked = multibar.stacked();
  344. if (onStateChange != null) {
  345. onStateChange(state);
  346. }
  347. dispatch.stateChange(state);
  348. chart.update();
  349. });
  350. dispatch.on('tooltipShow', function(e) {
  351. if (tooltips) showTooltip(e, that.parentNode)
  352. });
  353. // Update chart from a state object passed to event handler
  354. dispatch.on('changeState', function(e) {
  355. if (typeof e.disabled !== 'undefined') {
  356. data.forEach(function(series,i) {
  357. series.disabled = e.disabled[i];
  358. });
  359. state.disabled = e.disabled;
  360. }
  361. if (typeof e.stacked !== 'undefined') {
  362. multibar.stacked(e.stacked);
  363. state.stacked = e.stacked;
  364. }
  365. chart.update();
  366. });
  367. //============================================================
  368. function onBrush(){
  369. brushExtent = brush.empty() ? null : brush.extent();
  370. extent = brush.empty() ? x.domain() : brush.extent();
  371. dispatch.brush({extent: extent, brush: brush});
  372. }
  373. function onBrushEnd(){
  374. brushExtent = brush.empty() ? null : brush.extent();
  375. extent = brush.empty() ? x.domain() : brush.extent();
  376. if (onSelectRange != null){
  377. var _leftEdges = x.range();
  378. var _width = x.rangeBand();
  379. var _j;
  380. for(_j=0; extent[0] > (_leftEdges[_j] + _width); _j++) {}
  381. var _from = typeof x.domain()[_j] != "undefined" ? x.domain()[_j] : x.domain()[0];
  382. for(_j=0; extent[1] > (_leftEdges[_j] + _width); _j++) {}
  383. var _to = typeof x.domain()[_j] != "undefined" ? x.domain()[_j] : x.domain()[x.domain().length-1];
  384. onSelectRange(_from, _to);
  385. }
  386. }
  387. });
  388. return chart;
  389. }
  390. //============================================================
  391. // Event Handling/Dispatching (out of chart's scope)
  392. //------------------------------------------------------------
  393. multibar.dispatch.on('elementMouseover.tooltip', function(e) {
  394. e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top];
  395. dispatch.tooltipShow(e);
  396. });
  397. multibar.dispatch.on('elementMouseout.tooltip', function(e) {
  398. dispatch.tooltipHide(e);
  399. });
  400. dispatch.on('tooltipHide', function() {
  401. if (tooltips) nv.tooltip.cleanup();
  402. });
  403. //============================================================
  404. //============================================================
  405. // Expose Public Variables
  406. //------------------------------------------------------------
  407. // expose chart's sub-components
  408. chart.dispatch = dispatch;
  409. chart.multibar = multibar;
  410. chart.legend = legend;
  411. chart.xAxis = xAxis;
  412. chart.yAxis = yAxis;
  413. chart.LABELS = LABELS;
  414. d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'clipEdge',
  415. 'id', 'stacked', 'stackOffset', 'delay', 'barColor','groupSpacing');
  416. chart.options = nv.utils.optionsFunc.bind(chart);
  417. chart.margin = function(_) {
  418. if (!arguments.length) return margin;
  419. margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
  420. margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
  421. margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
  422. margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
  423. return chart;
  424. };
  425. chart.width = function(_) {
  426. if (!arguments.length) return width;
  427. width = _;
  428. return chart;
  429. };
  430. chart.height = function(_) {
  431. if (!arguments.length) return height;
  432. height = _;
  433. return chart;
  434. };
  435. chart.color = function(_) {
  436. if (!arguments.length) return color;
  437. color = nv.utils.getColor(_);
  438. legend.color(color);
  439. return chart;
  440. };
  441. chart.showControls = function(_) {
  442. if (!arguments.length) return showControls;
  443. showControls = _;
  444. return chart;
  445. };
  446. chart.showLegend = function(_) {
  447. if (!arguments.length) return showLegend;
  448. showLegend = _;
  449. return chart;
  450. };
  451. chart.showXAxis = function(_) {
  452. if (!arguments.length) return showXAxis;
  453. showXAxis = _;
  454. return chart;
  455. };
  456. chart.showYAxis = function(_) {
  457. if (!arguments.length) return showYAxis;
  458. showYAxis = _;
  459. return chart;
  460. };
  461. chart.rightAlignYAxis = function(_) {
  462. if(!arguments.length) return rightAlignYAxis;
  463. rightAlignYAxis = _;
  464. yAxis.orient( (_) ? 'right' : 'left');
  465. return chart;
  466. };
  467. chart.reduceXTicks= function(_) {
  468. if (!arguments.length) return reduceXTicks;
  469. reduceXTicks = _;
  470. return chart;
  471. };
  472. chart.rotateLabels = function(_) {
  473. if (!arguments.length) return rotateLabels;
  474. rotateLabels = _;
  475. return chart;
  476. }
  477. chart.staggerLabels = function(_) {
  478. if (!arguments.length) return staggerLabels;
  479. staggerLabels = _;
  480. return chart;
  481. };
  482. chart.tooltip = function(_) {
  483. if (!arguments.length) return tooltip;
  484. tooltip = _;
  485. return chart;
  486. };
  487. chart.tooltips = function(_) {
  488. if (!arguments.length) return tooltips;
  489. tooltips = _;
  490. return chart;
  491. };
  492. chart.tooltipContent = function(_) {
  493. if (!arguments.length) return tooltip;
  494. tooltip = _;
  495. return chart;
  496. };
  497. chart.state = function(_) {
  498. if (!arguments.length) return state;
  499. state = _;
  500. return chart;
  501. };
  502. chart.defaultState = function(_) {
  503. if (!arguments.length) return defaultState;
  504. defaultState = _;
  505. return chart;
  506. };
  507. chart.noData = function(_) {
  508. if (!arguments.length) return noData;
  509. noData = _;
  510. return chart;
  511. };
  512. chart.transitionDuration = function(_) {
  513. if (!arguments.length) return transitionDuration;
  514. transitionDuration = _;
  515. return chart;
  516. };
  517. chart.enableSelection = function() {
  518. selectionEnabled = true;
  519. return chart;
  520. };
  521. chart.onSelectRange = function(_) {
  522. if (!arguments.length) return onSelectRange;
  523. onSelectRange = _;
  524. return chart;
  525. };
  526. chart.onStateChange = function(_) {
  527. if (!arguments.length) return onStateChange;
  528. onStateChange = _;
  529. return chart;
  530. };
  531. chart.onChartUpdate = function(_) {
  532. if (!arguments.length) return onChartUpdate;
  533. onChartUpdate = _;
  534. return chart;
  535. };
  536. chart.selectBars = function(args) {
  537. if (!arguments.length) return selectBars;
  538. selectBars(args);
  539. return chart;
  540. };
  541. //============================================================
  542. return chart;
  543. }