nv.d3.multiBarWithBrushChart.js 19 KB

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