Boxplot.vue 16.3 KB
Newer Older
Sascha Herzinger's avatar
Sascha Herzinger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
  <div :class="`fjs-boxplot fjs-vm-uid-${this._uid}`">
    <div class="fjs-data-box-container">
      <data-box class="fjs-data-box"
                header="Numerical Variables"
                dataType="numerical"
                v-on:update="update_numData">
      </data-box>
      <data-box class="fjs-data-box"
                header="Categorical Variables"
                dataType="categorical"
                v-on:update="update_catData">
      </data-box>
    </div>

    <div class="fjs-parameter-container">
Sascha Herzinger's avatar
Sascha Herzinger committed
17
      <label for="fjs-show-data-check">Show Points</label>
18
      <input id="fjs-show-data-check" type="checkbox" v-model="params.showData"/>
Sascha Herzinger's avatar
Sascha Herzinger committed
19
20
21
22
      <label for="fjs-jitter-data-check">Jitter Data</label>
      <input id="fjs-jitter-data-check" type="checkbox" v-model="params.jitter"/>
      <label for="fjs-show-kde-check">Show Density Est.</label>
      <input id="fjs-show-kde-check" type="checkbox" v-model="params.showKDE"/>
Sascha Herzinger's avatar
Sascha Herzinger committed
23
24
25
26
27
28
    </div>

    <div class="fjs-vis-container">
      <svg :width="width"
           :height="height">
        <g :transform="`translate(${margin.left}, ${margin.top})`">
29
30
31
32
          <g class="fjs-boxplot-axis fjs-x-axis" :transform="`translate(0, ${padded.height})`"></g>
          <g class="fjs-boxplot-axis fjs-y-axis"></g>
          <g class="fjs-box"
             :transform="`translate(${scales.x(label)}, 0)`"
33
             :title="label"
34
35
36
             :data-label="label"
             @mouseenter="showTooltip(label)"
             @mouseleave="hideTooltip(label)"
Sascha Herzinger's avatar
Sascha Herzinger committed
37
             v-for="label in labels" >
38
39
            <line class="fjs-upper-whisker"
                  :title="results.statistics[label].u_wsk"
Sascha Herzinger's avatar
Sascha Herzinger committed
40
                  :x1="- boxplotWidth / 6"
Sascha Herzinger's avatar
Sascha Herzinger committed
41
                  :y1="tweened.boxes[label].u_wsk"
Sascha Herzinger's avatar
Sascha Herzinger committed
42
                  :x2="boxplotWidth / 6"
Sascha Herzinger's avatar
Sascha Herzinger committed
43
                  :y2="tweened.boxes[label].u_wsk">
44
45
            </line>
            <line class="fjs-lower-whisker"
Sascha Herzinger's avatar
Sascha Herzinger committed
46
                  :title="results.statistics.l_wsk"
47
                  :x1="- boxplotWidth / 6"
Sascha Herzinger's avatar
Sascha Herzinger committed
48
                  :y1="tweened.boxes[label].l_wsk"
49
                  :x2="boxplotWidth / 6"
Sascha Herzinger's avatar
Sascha Herzinger committed
50
                  :y2="tweened.boxes[label].l_wsk">
Sascha Herzinger's avatar
Sascha Herzinger committed
51
            </line>
52
53
            <line class="fjs-upper-quartile"
                  :title="results.statistics[label].u_qrt"
Sascha Herzinger's avatar
Sascha Herzinger committed
54
                  :x1="- boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
55
                  :y1="tweened.boxes[label].u_qrt"
Sascha Herzinger's avatar
Sascha Herzinger committed
56
                  :x2="boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
57
                  :y2="tweened.boxes[label].u_qrt">
58
59
            </line>
            <line class="fjs-lower-quartile"
Sascha Herzinger's avatar
Sascha Herzinger committed
60
                  :title="results.statistics.l_qrt"
61
                  :x1="- boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
62
                  :y1="tweened.boxes[label].l_qrt"
63
                  :x2="boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
64
                  :y2="tweened.boxes[label].l_qrt">
65
66
            </line>
            <line class="fjs-median"
Sascha Herzinger's avatar
Sascha Herzinger committed
67
                  :title="results.statistics.median"
68
                  :x1="- boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
69
                  :y1="tweened.boxes[label].median"
70
                  :x2="boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
71
                  :y2="tweened.boxes[label].median">
Sascha Herzinger's avatar
Sascha Herzinger committed
72
73
74
            </line>
            <line class="fjs-antenna"
                  :x1="0"
Sascha Herzinger's avatar
Sascha Herzinger committed
75
                  :y1="tweened.boxes[label].u_wsk"
Sascha Herzinger's avatar
Sascha Herzinger committed
76
                  :x2="0"
Sascha Herzinger's avatar
Sascha Herzinger committed
77
                  :y2="tweened.boxes[label].l_wsk">
Sascha Herzinger's avatar
Sascha Herzinger committed
78
79
80
            </line>
            <rect class="fjs-above-median-box"
                  :x="- boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
81
                  :y="tweened.boxes[label].u_qrt"
Sascha Herzinger's avatar
Sascha Herzinger committed
82
                  :width="boxplotWidth"
Sascha Herzinger's avatar
Sascha Herzinger committed
83
                  :height="tweened.boxes[label].median - tweened.boxes[label].u_qrt">
Sascha Herzinger's avatar
Sascha Herzinger committed
84
85
86
            </rect>
            <rect class="fjs-below-median-box"
                  :x="- boxplotWidth / 2"
Sascha Herzinger's avatar
Sascha Herzinger committed
87
                  :y="tweened.boxes[label].median"
Sascha Herzinger's avatar
Sascha Herzinger committed
88
                  :width="boxplotWidth"
Sascha Herzinger's avatar
Sascha Herzinger committed
89
                  :height="tweened.boxes[label].l_qrt - tweened.boxes[label].median">
Sascha Herzinger's avatar
Sascha Herzinger committed
90
            </rect>
91
            <circle class="fjs-points"
92
93
94
                    :title="point.tooltip"
                    :cx="point.jitter"
                    :cy="scales.y(point.value)"
95
96
97
98
                    r="4"
                    v-for="point in points[label]"
                    v-if="params.showData">
            </circle>
Sascha Herzinger's avatar
Sascha Herzinger committed
99
100
101
102
            <polyline class="fjs-kde"
                      :points="kdePolyPoints[label]"
                      v-if="params.showKDE">
            </polyline>
Sascha Herzinger's avatar
Sascha Herzinger committed
103
          </g>
Sascha Herzinger's avatar
Sascha Herzinger committed
104
105
106
        </g>
      </svg>
    </div>
107
    <task-view></task-view>
Sascha Herzinger's avatar
Sascha Herzinger committed
108
109
110
111
112
113
114
115
  </div>
</template>

<script>
  import DataBox from '../components/DataBox.vue'
  import store from '../../store/store'
  import requestHandling from '../methods/run-analysis'
  import * as d3 from 'd3'
Sascha Herzinger's avatar
Sascha Herzinger committed
116
  import { TweenLite } from 'gsap'
Sascha Herzinger's avatar
Sascha Herzinger committed
117
118
  import TaskView from '../components/TaskView.vue'
  import deepFreeze from 'deep-freeze-strict'
119
  import utils from '../../services/utils'
120
  import tippy from 'tippy.js'
Sascha Herzinger's avatar
Sascha Herzinger committed
121
122
123
124
125
126
127
128
  export default {
    name: 'boxplot',
    data () {
      return {
        width: 0,
        height: 0,
        numData: [],
        catData: [],
129
130
131
        tooltips: {
          boxes: {}
        },
132
        params: {
Sascha Herzinger's avatar
Sascha Herzinger committed
133
134
135
          showData: false,
          jitter: false,
          showKDE: false
136
        },
Sascha Herzinger's avatar
Sascha Herzinger committed
137
138
139
        results: {
          data: [],
          statistics: {}
Sascha Herzinger's avatar
Sascha Herzinger committed
140
141
142
        },
        tweened: {
          boxes: {}
Sascha Herzinger's avatar
Sascha Herzinger committed
143
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
144
145
146
      }
    },
    computed: {
147
148
149
      idFilter () {
        return store.getters.filter('ids')
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
150
151
      args () {
        return {
152
153
          variables: this.numData,
          categories: this.catData,
154
          id_filter: this.idFilter,
Sascha Herzinger's avatar
Sascha Herzinger committed
155
156
157
158
159
160
161
          subsets: store.getters.subsets
        }
      },
      validArgs () {
        return this.numData.length > 0
      },
      margin () {
162
        const left = 60
Sascha Herzinger's avatar
Sascha Herzinger committed
163
        const top = 10
Sascha Herzinger's avatar
Sascha Herzinger committed
164
165
        const right = 50
        const bottom = this.height * 0.1
Sascha Herzinger's avatar
Sascha Herzinger committed
166
167
168
169
170
171
172
        return { left, top, right, bottom }
      },
      padded () {
        const width = this.width - this.margin.left - this.margin.right
        const height = this.height - this.margin.top - this.margin.bottom
        return { width, height }
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
173
174
175
      labels () {
        return Object.keys(this.results.statistics)
      },
176
177
      points () {
        const points = {}
Sascha Herzinger's avatar
Sascha Herzinger committed
178
        this.labels.forEach(label => {
179
180
181
182
          let [variable, category, subset] = label.split('//')
          subset = parseInt(subset.substring(1)) - 1  // revert subset string formatting
          points[label] = this.results.data
            .filter(d => d.subset === subset && d.category === category)
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
            .map(d => {
              return {
                id: d.id,
                value: d[variable],
                jitter: this.params.jitter ? Math.random() * this.boxplotWidth / 2 : this.boxplotWidth / 2,
                subset: d.subset,
                category: d.category,
                get tooltip () {
                  return `
<div>
  <p>${variable}: ${this.value}</p>
  <p>Category: ${this.category}</p>
  <p>Subset: ${this.subset + 1}</p>
</div>
`
                }
              }
            })
201
202
203
        })
        return points
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
204
205
206
207
208
209
210
211
212
213
214
215
216
      boxes () {
        const boxes = {}
        this.labels.forEach(label => {
          boxes[label] = {
            u_wsk: this.scales.y(this.results.statistics[label].u_wsk),
            l_wsk: this.scales.y(this.results.statistics[label].l_wsk),
            u_qrt: this.scales.y(this.results.statistics[label].u_qrt),
            l_qrt: this.scales.y(this.results.statistics[label].l_qrt),
            median: this.scales.y(this.results.statistics[label].median)
          }
        })
        return boxes
      },
217
      numOfBoxplots () {
Sascha Herzinger's avatar
Sascha Herzinger committed
218
        return this.labels.length
219
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
220
      boxplotWidth () {
221
        const maxBoxplotWidth = this.padded.width / 4
222
        const minBoxplotWidth = 10
223
224
        let boxplotWidth = this.padded.width / this.numOfBoxplots - this.padded.width * 0.05
        boxplotWidth = boxplotWidth > maxBoxplotWidth ? maxBoxplotWidth : boxplotWidth
225
        boxplotWidth = boxplotWidth < minBoxplotWidth ? minBoxplotWidth : boxplotWidth
226
227
228
229
230
231
        return boxplotWidth
      },
      scales () {
        const values = this.results.data.map(entry => this.results.variables.map(v => entry[v]))
        const flattened = [].concat.apply([], values)
        const extent = d3.extent(flattened)
Sascha Herzinger's avatar
Sascha Herzinger committed
232
        const padding = (extent[1] - extent[0]) / 20
Sascha Herzinger's avatar
Sascha Herzinger committed
233
        const x = d3.scalePoint()
Sascha Herzinger's avatar
Sascha Herzinger committed
234
          .domain(this.labels)
Sascha Herzinger's avatar
Sascha Herzinger committed
235
          .range([0, this.padded.width])
236
          .padding(0.5)
237
        const y = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
238
          .domain([extent[0] - padding, extent[1] + padding])
Sascha Herzinger's avatar
Sascha Herzinger committed
239
          .range([this.padded.height, 0])
Sascha Herzinger's avatar
Sascha Herzinger committed
240
241
        return { x, y }
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
      kdePolyPoints () {
        const polyPoints = {}
        this.labels.forEach(label => {
          polyPoints[label] = this.results.statistics[label].kde.map((d, i) => {
            return -this.kdeScales[label].y(d) + ',' + this.kdeScales[label].x(i)
          }).join(' ')
        })
        return polyPoints
      },
      kdeScales () {
        const polyPoints = {}
        this.labels.forEach(label => {
          const x = d3.scaleLinear()
            .domain([0, this.results.statistics[label].kde.length - 1])
            .range([this.scales.y(this.results.statistics[label].l_wsk),
              this.scales.y(this.results.statistics[label].u_wsk)])
          const y = d3.scaleLinear()
            .domain(d3.extent(this.results.statistics[label].kde))
            .range([0, this.boxplotWidth / 2])
          polyPoints[label] = { x, y }
        })
        return polyPoints
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
265
      axis () {
Sascha Herzinger's avatar
Sascha Herzinger committed
266
        const x = d3.axisBottom(this.scales.x).tickFormat(d => utils.truncate({fullStr: d, strLen: 35}))
Sascha Herzinger's avatar
Sascha Herzinger committed
267
        const y = d3.axisLeft(this.scales.y)
268
        return { x, y }
Sascha Herzinger's avatar
Sascha Herzinger committed
269
270
      }
    },
271
272
273
    // IMPORTANT: If the code within the watchers does interact with the DOM the code should be wrapped into a $nextTick
    // statement. This helps with the integration into the Vue component lifecycle. E.g.: an animation can't be
    // applied to an element that does not exist yet.
Sascha Herzinger's avatar
Sascha Herzinger committed
274
    watch: {
Sascha Herzinger's avatar
Sascha Herzinger committed
275
276
277
278
279
280
281
282
283
284
285
      'boxes': {
        handler: function (newBoxes) {
          Object.keys(newBoxes).forEach(label => {
            if (typeof this.tweened.boxes[label] === 'undefined') {
              this.$set(this.tweened.boxes, label, newBoxes[label])
            } else {
              TweenLite.to(this.tweened.boxes[label], 0.5, newBoxes[label])
            }
          })
        }
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
286
287
288
289
290
291
292
293
294
      'args': {
        handler: function (newArgs, oldArgs) {
          // if our data selection change we will want to re-initialize the current view
          const init = JSON.stringify(newArgs.variables) !== JSON.stringify(oldArgs.variables) ||
            JSON.stringify(newArgs.categories) !== JSON.stringify(oldArgs.categories)
          if (this.validArgs) {
            this.runAnalysisWrapper({init, args: this.args})
          }
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
295
296
297
      },
      'axis': {
        handler: function (newAxis) {
298
299
300
301
302
303
304
305
306
          this.$nextTick(() => {
            d3.select(`.fjs-vm-uid-${this._uid} .fjs-x-axis`)
              .call(newAxis.x)
              .selectAll('text')
              .attr('transform', 'rotate(20)')
            d3.select(`.fjs-vm-uid-${this._uid} .fjs-y-axis`)
              .call(newAxis.y)
          })
        }
307
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
308
309
310
311
312
313
314
315
316
317
318
319
      'points': {
        handler: function () {
          // https://github.com/atomiks/tippyjs/issues/74
          if (typeof this.tooltips.points !== 'undefined') {
            this.tooltips.points.destroyAll()
          }
          this.$nextTick(() => {
            this.tooltips.points = tippy(`.fjs-vm-uid-${this._uid} .fjs-points:not([data-tooltipped])`, {
              performance: true,
              theme: 'light',
              arrow: true
            })
320
          })
Sascha Herzinger's avatar
Sascha Herzinger committed
321
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
322
323
324
      }
    },
    methods: {
325
      showTooltip (label) {
326
        // https://github.com/atomiks/tippyjs/issues/74
327
328
        Object.keys(this.tooltips.boxes).forEach(label => this.tooltips.boxes[label].forEach(d => d.tip.destroyAll()))
        this.tooltips.boxes = {}
329

330
331
332
333
334
335
336
337
338
339
340
        const defaultOptions = {
          performance: true,
          theme: 'light',
          arrow: true,
          trigger: 'manual'
        }
        const upperWhisker = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"] .fjs-upper-whisker`)
        const lowerWhisker = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"] .fjs-lower-whisker`)
        const upperQuartile = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"] .fjs-upper-quartile`)
        const lowerQuartile = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"] .fjs-lower-quartile`)
        const median = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"] .fjs-median`)
341
342
        const box = document.querySelector(`.fjs-vm-uid-${this._uid} .fjs-box[data-label="${label}"]`)
        this.tooltips.boxes[label] = [
343
344
345
346
          { tip: tippy(upperWhisker, Object.assign({position: 'right'}, defaultOptions)), el: upperWhisker },
          { tip: tippy(lowerWhisker, Object.assign({position: 'right'}, defaultOptions)), el: lowerWhisker },
          { tip: tippy(upperQuartile, Object.assign({position: 'left'}, defaultOptions)), el: upperQuartile },
          { tip: tippy(lowerQuartile, Object.assign({position: 'left'}, defaultOptions)), el: lowerQuartile },
347
348
          { tip: tippy(median, Object.assign({position: 'right'}, defaultOptions)), el: median },
          { tip: tippy(box, Object.assign({position: 'bottom'}, defaultOptions)), el: box }
349
        ]
350
        this.tooltips.boxes[label].forEach(d => {
351
352
353
354
          d.tip.show(d.tip.getPopperElement(d.el))
        })
      },
      hideTooltip (label) {
355
        this.tooltips.boxes[label].forEach(d => d.tip.hide(d.tip.getPopperElement(d.el)))
356
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
      update_numData (ids) {
        this.numData = ids
      },
      update_catData (ids) {
        this.catData = ids
      },
      handleResize () {
        const container = this.$el.querySelector(`.fjs-vm-uid-${this._uid} .fjs-vis-container svg`)
        // noinspection JSSuspiciousNameCombination
        this.height = container.getBoundingClientRect().width
        this.width = container.getBoundingClientRect().width
      },
      runAnalysisWrapper ({args}) {
        // function made available via requestHandling mixin
        this.runAnalysis({task_name: 'compute-boxplot', args})
          .then(response => {
            const results = JSON.parse(response)
            const data = JSON.parse(results.data)
            results.data = Object.keys(data).map(key => data[key])
            deepFreeze(results) // massively improve performance by telling Vue that the objects properties won't change
            this.results = results
378
            this.handleResize()
Sascha Herzinger's avatar
Sascha Herzinger committed
379
380
381
382
383
384
385
386
387
          })
          .catch(error => console.error(error))
      }
    },
    components: {
      DataBox,
      TaskView
    },
    mixins: [
388
      requestHandling
Sascha Herzinger's avatar
Sascha Herzinger committed
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
    ],
    mounted () {
      window.addEventListener('resize', this.handleResize)
      this.handleResize()
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.handleResize)
    }
  }
</script>

<style lang="sass" scoped>
  @import './src/assets/base.sass'

  *
    font-family: Roboto, sans-serif

  .fjs-boxplot
    height: 100%
    width: 100%
    display: flex
    flex-direction: column

    .fjs-data-box-container
      height: 160px
      display: flex
      justify-content: space-around

    .fjs-vis-container
      flex: 1
      display: flex
420
421
      .fjs-tooltip
        position: absolute
Sascha Herzinger's avatar
Sascha Herzinger committed
422
423
      svg
        flex: 1
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        .fjs-box
          .fjs-median, .fjs-lower-quartile, .fjs-upper-quartile
            opacity: 1
          .fjs-lower-whisker, .fjs-upper-whisker, .fjs-antenna
            shape-rendering: crispEdges
            stroke: black
            stroke-width: 2px
          .fjs-below-median-box
            stroke: none
            fill: rgb(205, 232, 254)
            shape-rendering: crispEdges
          .fjs-above-median-box
            stroke: none
            fill: rgb(180, 221, 253)
            shape-rendering: crispEdges
439
        .fjs-points
440
          stroke: none
Sascha Herzinger's avatar
Sascha Herzinger committed
441
442
443
444
        .fjs-kde
          fill: none
          stroke: black
          stroke-width: 2px
Sascha Herzinger's avatar
Sascha Herzinger committed
445
446
447
448
449
</style>


<!--CSS for dynamically created components-->
<style lang="sass">
450
  .fjs-boxplot-axis
Sascha Herzinger's avatar
Sascha Herzinger committed
451
452
453
454
    shape-rendering: crispEdges
    stroke-width: 2px
    .tick
      shape-rendering: crispEdges
Sascha Herzinger's avatar
Sascha Herzinger committed
455
456
      text
        font-size: 18px
Sascha Herzinger's avatar
Sascha Herzinger committed
457
458
    line
      stroke: #999
Sascha Herzinger's avatar
Sascha Herzinger committed
459
460
461
462
  .fjs-x-axis
    .tick
      text
        text-anchor: start
Sascha Herzinger's avatar
Sascha Herzinger committed
463
        font-size: 14px
Sascha Herzinger's avatar
Sascha Herzinger committed
464
</style>