google-chart.html 15.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="/bower_components/google-apis/google-legacy-loader.html">
<link rel="import" href="/bower_components/iron-icons/iron-icons.html">
<link rel="import" href="/bower_components/iron-icons/maps-icons.html">
<link rel="import" href="/bower_components/paper-icon-button/paper-icon-button.html">

<!--
`google-chart` encapsulates Google Charts as a web component, allowing you to easily visualize
data. From simple line charts to complex hierarchical tree maps, the chart element provides a
number of ready-to-use chart types.
    <google-chart
      type='pie'
      options='{"title": "Distribution of days in 2001Q1"}'
      cols='[{"label":"Month", "type":"string"}, {"label":"Days", "type":"number"}]'
      rows='[["Jan", 31],["Feb", 28],["Mar", 31]]'>
    </google-chart>
Height and width are specified as style attributes:
    google-chart {
      height: 300px;
      width: 50em;
    }
Data can be provided in one of three ways:
- Via the `cols` and `rows` attributes:
      cols='[{"label":"Mth", "type":"string"}, {"label":"Days", "type":"number"}]'
      rows='[["Jan", 31],["Feb", 28],["Mar", 31]]'
- Via the `data` attribute, passing in the data directly:
      data='[["Month", "Days"], ["Jan", 31], ["Feb", 28], ["Mar", 31]]'
- Via the `data` attribute, passing in the URL to a resource containing the
  data, in JSON format:
      data='http://example.com/chart-data.json'
@demo
-->
<dom-module id="google-chart">
<style is="custom-style">
  @import url("../../styles/app-theme.html");
</style>
<link rel="import" type="css" href="google-chart.css">
<template>
  <paper-material elevation="1">
    <div class="top-bar">
      <iron-icon icon="{{icon}}"></iron-icon>
      <span>{{options.title}}</span>
    </div>
45
    <div id="nodata">No entries match the current filters</div>
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
    <iron-ajax id="ajax" handle-as="json" url="{{data}}"
    on-response="_externalDataLoaded"></iron-ajax>
    <div id="chartdiv"></div>
    <google-legacy-loader on-api-load="_readyForAction"></google-legacy-loader>

    <div style="float:right">
      <small>Clear Filters</small>
      <paper-icon-button icon="delete" alt="menu" class="green" on-tap="removeFilters"></paper-icon-button>
    </div>
    <div style="width:100%; clear: both"></div>
  </paper-material>
</template>
</dom-module>

<script>
  var filtered = false;
  (function() {
    "use strict";
    Polymer({
      is: 'google-chart',
    /**
     * Fired when the graph is displayed.
     *
     * @event google-chart-render
     */
    /**
     * Fired when the user makes a selection in the chart.
     *
     * @event google-chart-select
     * @param {object} detail
     *   @param {array} detail.selection The user-defined selection.
     */
     properties: {
      /**
       * Sets the type of the chart.
       *
       * Should be one of:
       * - `area`, `bar`, `bubble`, `candlestick`, `column`, `combo`, `geo`,
       *   `histogram`, `line`, `pie`, `scatter`, `stepped-area`, `treemap`
       *
       * See <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery">Google Visualization API reference (Chart Gallery)</a> for details.
       *
       */
       type: {
        type: String,
        value: 'column',
        observer: '_typeChanged'
      },
      data: {
        type: Object,
        observer: '_dataChanged'              
      },
      /**
       * Sets the options for the chart.
       *
       * Example:
       * <pre>{
       *   title: "Chart title goes here",
       *   hAxis: {title: "Categories"},
       *   vAxis: {title: "Values", minValue: 0, maxValue: 2},
       *   legend: "none"
       * };</pre>
       * See <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery">Google Visualization API reference (Chart Gallery)</a>
       * for the options available to each chart type.
       *
       */
       options: {
        type: Object,
        value: function() { return {}; }
      },
      optionsbi: {
        type: Object,
        value: function() { return {}; }
      },
      intvalue:{
        type: Number,
        value: 0
      },
      /**
       * Sets the data columns for this object.
       *
       * When specifying data with `cols` you must also specify `rows`, and
       * not specify `data`.
       *
       * Example:
       * <pre>[{label: "Categories", type: "string"},
       *  {label: "Value", type: "number"}]</pre>
       * See <a href="https://google-developers.appspot.com/chart/interactive/docs/reference#DataTable_addColumn">Google Visualization API reference (addColumn)</a>
       * for column definition format.
       *
       * @attribute cols
       * @type array
       */
       cols: {
        type: Array,
        value: function() { return []; }
      },
      /**
       * Sets the data rows for this object.
       *
       * When specifying data with `rows` you must also specify `cols`, and
       * not specify `data`.
       *
       * Example:
       * <pre>[["Category 1", 1.0],
       *  ["Category 2", 1.1]]</pre>
       * See <a href="https://google-developers.appspot.com/chart/interactive/docs/reference#addrow">Google Visualization API reference (addRow)</a>
       * for row format.
       *
       * @attribute rows
       * @type array
       */
       rows: {
        type: Array,
        value: function() { return []; }
      },
      /**
       * Sets the entire dataset for this object.
       * Can be used to provide the data directly, or to provide a URL from
       * which to request the data.
       *
       * The data format can be a two-dimensional array or the DataTable format
       * expected by Google Charts.
       * See <a href="https://google-developers.appspot.com/chart/interactive/docs/reference#DataTable">Google Visualization API reference (eataTable constructor)</a>
       * for data table format details.
       *
       * When specifying data with `data` you must not specify `cols` or `rows`.
       *
       * Example:
       * <pre>[["Categories", "Value"],
       *  ["Category 1", 1.0],
       *  ["Category 2", 1.1]]</pre>
       *
       * @attribute data
       * @type array, object, or string
       */
      /**
       * Selected datapoint(s) in the map.
       *
       * An array of objects, each with a numeric row and/or column property.
       * `row` and `column` are the zero-based row or column number of an item
       * in the data table to select.
       *
       * To select a whole column, set row to null;
       * to select a whole row, set column to null.
       *
       * Example:
       * <pre>
       *   [{row:0,column:1}, {row:1, column:null}]
       * </pre>
       *
       * @attribute selection
       * @type array
       */
       selection: {
        type: Array,
        value: function() { return []; },
        observer: '_selectionChanged'
      },

      query: {
        type: String,
        observer: '_queryChanged'
      },

      index: {
        type: String
      },

      subindex: {
        type: String
      },

      extraId: {
        type: String
      },

      fields: {
        type: Array,
        value: function() { return []; }
      },

      field: {
        type: String
      },

      host: {
        type: String
      },

      icon: {
        type: String
      },

      param: {
        type: String,
        notify: true
      },

      filters: {
        type: Array,
        notify: true,
        value: function() { return []; }
      }, 
      isSelected: {
        type: Boolean,
        value: false
      }
    },

    _packages: null,
    _chartObject: null,
    _isReady: false,
    _canDraw: false,
    _dataTable: null,
    _chartTypes: null,
    _readyForAction: function(e, detail, sender) {
      this._loadPackageByChartType();
      google.load("visualization", "1", {
        packages: this._packages[this.type],
        callback: function() {
          this._isReady = true;
          this._loadChartTypes();
          this._loadData();
        }.bind(this)
      });
    },

    _typeChanged: function() {
      // Invalidate current chart object.
      this._chartObject = null;
      this._loadData();
    },

    _selectionChanged: function() {
      //console.log("_selectionChanged")
      if(this.selection.length != 0){
        var arr = this.rows;
        var sel = this.selection[0].row
        this.param = arr[sel][0]
        var param = this.param
        var field = this.field
        var term1 = {};
        console.log(param.toLowerCase())
        if (field == "sentiment") field = 'sentiments.marl:hasPolarity'
        if (field == "emotion") field = 'emotions.onyx:hasEmotion.onyx:hasEmotionCategory'
        term1[field] = param.toLowerCase().split(" ");
Alberto Pascual's avatar
Alberto Pascual committed
293
        if (field == 'datePublished'){
294
295
           term1[field] = param.toLowerCase().split("-");
        }
296
297
        console.log(term1)
        var object = {terms: term1}
Alberto Pascual's avatar
Alberto Pascual committed
298
        if (field == 'schema:datePublished'){
299
300
           var date = param.toLowerCase().toString().split("-");
           var term = date[1]+'-'+date[0]+'-01'
Alberto Pascual's avatar
Alberto Pascual committed
301
           object = {range: {'schema:datePublished': {gte: term, boost: 5}}}
302
        }
303
304
305
306
307
308
        var isInside = -1
        for(var i = 0; i < this.filters.length; i++){
          if(JSON.stringify(this.filters[i].term) === JSON.stringify(term1))
              isInside = i
        }
        if(isInside == -1){
309
          this.push('filters', object)
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
          this.isSelected = true
        }
      } else {
        if(this.isSelected)
          for(var i = 0; i < this.filters.length; i++){
            if(Object.keys(this.filters[i].term)[0] === this.field){
              this.filters.splice(i,1)
              this.isSelected = false
            }
          }
      }
    },

    ready: function() {

      this.type == 'table' ? this.$.chartdiv.style.margin = '2% 0 2% 33%' : undefined
    },

    removeFilters: function(){
      this.filters = [];
      this.selection = [];
    },

    /**
     * Draws the chart.
     *
     * Called automatically on first load and whenever one of the attributes
     * changes. Can be called manually to handle e.g. page resizes.
     *
     * @method drawChart
     * @return {Object} Returns null.
     */
     drawChart: function() {
      //console.log("inside drawing")
      if (this._canDraw) {
        if (!this.options) {
          this.options = {};
        }
        if (!this._chartObject) {
          var chartClass = this._chartTypes[this.type];
          if (chartClass) {
            this._chartObject = new chartClass(this.$.chartdiv)
            //console.log(this._chartObject)
          }
        }
      }
      this._enableobserver();
      return null;
    },

    _enableobserver: function(){
      if (this._chartObject) {
        google.visualization.events.addOneTimeListener(this._chartObject,
            'ready', function() {
              this.fire('google-chart-render');
            }.bind(this));
          google.visualization.events.addListener(this._chartObject,
            'select', function() {
              //console.log("seleccionando")
              this.selection = this._chartObject.getSelection();
              this.fire('google-chart-select',
                { selection: this._chartObject.getSelection() });
            }.bind(this));
          this._chartObject.draw(this._dataTable, this.optionsbi);
      } else {
          this.$.chartdiv.innerHTML = 'Undefined chart type';
      }

    },

    _loadChartTypes: function() {
      this._chartTypes = {
        'area': google.visualization.AreaChart,
        'bar': google.visualization.BarChart,
        'bubble': google.visualization.BubbleChart,
        'candlestick': google.visualization.CandlestickChart,
        'column': google.visualization.ColumnChart,
        'combo': google.visualization.ComboChart,
        'geo': google.visualization.GeoChart,
        'histogram': google.visualization.Histogram,
        'line': google.visualization.LineChart,
        'pie': google.visualization.PieChart,
        'scatter': google.visualization.ScatterChart,
        'stepped-area': google.visualization.SteppedAreaChart,
        'table': google.visualization.Table,
        'gauge': google.visualization.Gauge,
        'treemap': google.visualization.TreeMap
      };
    },

    _loadPackageByChartType: function() {
      this._packages = {
        'area': 'corechart',
        'bar': 'corechart',
        'bubble': 'corechart',
        'candlestick': 'corechart',
        'column': 'corechart',
        'combo': 'corechart',
        'geo': 'corechart',
        'histogram': 'corechart',
        'line': 'corechart',
        'pie': 'corechart',
        'scatter': 'corechart',
        'stepped-area': 'corechart',
        'table': 'table',
        'gauge': 'gauge',
        'treemap': 'treemap'
      };
    },

    _loadData: function() {
      //console.log("dataloaded")
      this._canDraw = false;
      if (this._isReady) {
        if (typeof this.data == 'string' || this.data instanceof String) {
          // Load data asynchronously, from external URL.
          this.$.ajax.generateRequest();
        } else {
          var dataTable = this._createDataTable();
          this._canDraw = true;
          if (dataTable) {
            this._dataTable = dataTable;
            //console.log(this.intvalue)
            if (this.intvalue == 0){
              this.drawChart();
              this.intvalue++
            }
            if(this.intvalue != 0){
              this._chartObject.draw(this._dataTable, this.optionsbi);
            }
          }
        }
      }
    },

    _externalDataLoaded: function(e) {
      var dataTable = this._createDataTable(e.detail.response);
      this._canDraw = true;
      this._dataTable = dataTable;
      this.drawChart();
    },

    _createDataTable: function(data) {
      var dataTable = null;
      // If a data object was not passed to this function, default to the
      // chart's data attribute. Passing a data object is necessary for
      // cases when the data attribute is a URL pointing to an external
      // data source.
      if (!data) {
        data = this.data;
      }
      if (!data)
        data = [];
      if (this.rows && this.rows.length > 0 && this.cols &&
        this.cols.length > 0) {
        // Create the data table from cols and rows.
      dataTable = new google.visualization.DataTable();
      dataTable.cols = this.cols;
      for (var i = 0; i < this.cols.length; i++) {
        dataTable.addColumn(this.cols[i]);
      }
      dataTable.addRows(this.rows);
    } else {
        // Create dataTable from the passed data or the data attribute.
        // Data can be in the form of raw DataTable data or a two
        // dimensional array.
        if (data.rows && data.cols) {
          dataTable = new google.visualization.DataTable(data);
        } else if (data.length > 0) {
          dataTable = google.visualization.arrayToDataTable(data);
        }
      }
      return dataTable;
    },

    _dataChanged: function() {
      //console.log("_dataChanged")
Alberto Pascual's avatar
Alberto Pascual committed
487
488
      //console.log(this.field)
      //console.log(this.data)
489
490
491
492
493
494
495
496
497
      var that = this
      var aggs = 0
      try{
        var hits = this.data.aggregations[this.field].buckets;
      }
      catch(err){
        var hits = []
      }
      var data = [];
Alberto Pascual's avatar
Alberto Pascual committed
498
      if (this.field == "schema:datePublished") {
499
500
501
502
503
504
505
506
507
        hits.forEach(function(entry) {
          data.push([entry.key_as_string, entry.doc_count]);
        });
      }
      else {
        hits.forEach(function(entry) {
          data.push([entry.key, entry.doc_count]);
        });
      }
Alberto Pascual's avatar
Alberto Pascual committed
508
      //console.log(data)
509
510
511
512
513
514
515
516
       if(data.length == 0 ){
          this.$.chartdiv.style.visibility = 'hidden';
          this.$.nodata.style.visibility = 'visible';
      } else {
          this.$.chartdiv.style.visibility = 'visible';
          this.$.nodata.style.visibility = 'hidden';
      }

517
518
519
520
521
522
523
524
525
      that.rows = data;
      filtered = true;
      this._loadData();
    }

    
  });
})();
</script>