nv.d3.lineWithBrushChart.js 17 KB

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