nv.d3.lineWithBrushChart.js 18 KB

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