1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 tvcm.require('tvcm.range');
8 tvcm.require('tvcm.ui.d3');
9 tvcm.require('tvcm.ui.chart_base');
11 tvcm.requireStylesheet('tvcm.ui.line_chart');
13 tvcm.exportTo('tvcm.ui', function() {
14 var ChartBase = tvcm.ui.ChartBase;
15 var getColorOfKey = tvcm.ui.getColorOfKey;
20 var LineChart = tvcm.ui.define('line-chart', ChartBase);
22 LineChart.prototype = {
23 __proto__: ChartBase.prototype,
25 decorate: function() {
26 ChartBase.prototype.decorate.call(this);
27 this.classList.add('line-chart');
29 this.xScale_ = d3.scale.linear();
30 this.yScale_ = d3.scale.linear();
31 d3.select(this.chartAreaElement)
33 .attr('id', 'series');
37 * Sets the data array for the object
39 * @param {Array} data The data. Each element must be an object, with at
40 * least an x property. All other properties become series names in the
45 throw new Error('Data must be nonzero. Pass undefined.');
48 if (data !== undefined) {
50 if (d.x === undefined)
51 throw new Error('Elements must have "x" fields');
52 keys = d3.keys(data[0]);
53 keys.splice(keys.indexOf('x'), 1);
55 throw new Error('Elements must have at least one other field than X');
60 this.seriesKeys_ = keys;
62 this.updateContents_();
65 getLegendKeys_: function() {
66 if (this.seriesKeys_ &&
67 this.seriesKeys_.length > 1)
68 return this.seriesKeys_.slice();
72 updateScales_: function(width, height) {
73 if (this.data_ === undefined)
77 this.xScale_.range([0, width]);
78 this.xScale_.domain(d3.extent(this.data_, function(d) { return d.x; }));
81 var yRange = new tvcm.Range();
82 this.data_.forEach(function(d) {
83 this.seriesKeys_.forEach(function(k) {
84 yRange.addValue(d[k]);
88 this.yScale_.range([height, 0]);
89 this.yScale_.domain([yRange.min, yRange.max]);
92 updateContents_: function() {
93 ChartBase.prototype.updateContents_.call(this);
97 var chartAreaSel = d3.select(this.chartAreaElement);
98 var seriesSel = chartAreaSel.select('#series');
99 var pathsSel = seriesSel.selectAll('path').data(this.seriesKeys_);
102 .attr('class', 'line')
103 .style('stroke', function(key) {
104 return getColorOfKey(key);
106 .attr('d', function(key) {
107 var line = d3.svg.line()
108 .x(function(d) { return this.xScale_(d.x); }.bind(this))
109 .y(function(d) { return this.yScale_(d[key]); }.bind(this));
110 return line(this.data_);
112 pathsSel.exit().remove();