nv.d3.lineWithBrushChart.js 17 KB

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