nv.d3.multiBarWithFocusChart.js 18 KB

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