Boxplot.vue 12.7 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">
17
18
      <label for="fjs-show-data-check">Show Data Points</label>
      <input id="fjs-show-data-check" type="checkbox" v-model="params.showData"/>
Sascha Herzinger's avatar
Sascha Herzinger committed
19
20
21
22
23
24
    </div>

    <div class="fjs-vis-container">
      <svg :width="width"
           :height="height">
        <g :transform="`translate(${margin.left}, ${margin.top})`">
25
26
27
28
29
30
31
32
33
34
          <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)`"
             :data-label="label"
             @mouseenter="showTooltip(label)"
             @mouseleave="hideTooltip(label)"
             v-for="label in Object.keys(results.statistics)" >
            <line class="fjs-upper-whisker"
                  :title="results.statistics[label].u_wsk"
Sascha Herzinger's avatar
Sascha Herzinger committed
35
                  :x1="- boxplotWidth / 6"
36
                  :y1="scales.y(results.statistics[label].u_wsk)"
Sascha Herzinger's avatar
Sascha Herzinger committed
37
                  :x2="boxplotWidth / 6"
38
39
40
41
42
43
44
45
                  :y2="scales.y(results.statistics[label].u_wsk)">
            </line>
            <line class="fjs-lower-whisker"
                  :title="results.statistics[label].l_wsk"
                  :x1="- boxplotWidth / 6"
                  :y1="scales.y(results.statistics[label].l_wsk)"
                  :x2="boxplotWidth / 6"
                  :y2="scales.y(results.statistics[label].l_wsk)">
Sascha Herzinger's avatar
Sascha Herzinger committed
46
            </line>
47
48
            <line class="fjs-upper-quartile"
                  :title="results.statistics[label].u_qrt"
Sascha Herzinger's avatar
Sascha Herzinger committed
49
                  :x1="- boxplotWidth / 2"
50
                  :y1="scales.y(results.statistics[label].u_qrt)"
Sascha Herzinger's avatar
Sascha Herzinger committed
51
                  :x2="boxplotWidth / 2"
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
                  :y2="scales.y(results.statistics[label].u_qrt)">
            </line>
            <line class="fjs-lower-quartile"
                  :title="results.statistics[label].l_qrt"
                  :x1="- boxplotWidth / 2"
                  :y1="scales.y(results.statistics[label].l_qrt)"
                  :x2="boxplotWidth / 2"
                  :y2="scales.y(results.statistics[label].l_qrt)">
            </line>
            <line class="fjs-median"
                  :title="results.statistics[label].median"
                  :x1="- boxplotWidth / 2"
                  :y1="scales.y(results.statistics[label].median)"
                  :x2="boxplotWidth / 2"
                  :y2="scales.y(results.statistics[label].median)">
Sascha Herzinger's avatar
Sascha Herzinger committed
67
68
69
70
71
72
73
74
75
            </line>
            <line class="fjs-antenna"
                  :x1="0"
                  :y1="scales.y(results.statistics[label].u_wsk)"
                  :x2="0"
                  :y2="scales.y(results.statistics[label].l_wsk)">
            </line>
            <rect class="fjs-above-median-box"
                  :x="- boxplotWidth / 2"
76
                  :y="scales.y(results.statistics[label].u_qrt)"
Sascha Herzinger's avatar
Sascha Herzinger committed
77
78
79
80
81
82
83
                  :width="boxplotWidth"
                  :height="scales.y(results.statistics[label].median) - scales.y(results.statistics[label].u_qrt)">
            </rect>
            <rect class="fjs-below-median-box"
                  :x="- boxplotWidth / 2"
                  :y="scales.y(results.statistics[label].median)"
                  :width="boxplotWidth"
84
                  :height="scales.y(results.statistics[label].l_qrt) - scales.y(results.statistics[label].median)">
Sascha Herzinger's avatar
Sascha Herzinger committed
85
            </rect>
86
87
88
89
90
91
            <circle class="fjs-points"
                    :cy="scales.y(point)"
                    r="4"
                    v-for="point in points[label]"
                    v-if="params.showData">
            </circle>
Sascha Herzinger's avatar
Sascha Herzinger committed
92
          </g>
Sascha Herzinger's avatar
Sascha Herzinger committed
93
94
95
        </g>
      </svg>
    </div>
96
    <task-view></task-view>
Sascha Herzinger's avatar
Sascha Herzinger committed
97
98
99
100
101
102
103
104
105
106
  </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'
  import TaskView from '../components/TaskView.vue'
  import deepFreeze from 'deep-freeze-strict'
107
  import utils from '../../services/utils'
108
  import tippy from 'tippy.js'
Sascha Herzinger's avatar
Sascha Herzinger committed
109
110
111
112
113
114
115
116
  export default {
    name: 'boxplot',
    data () {
      return {
        width: 0,
        height: 0,
        numData: [],
        catData: [],
117
        tooltips: {},
118
119
120
        params: {
          showData: false
        },
Sascha Herzinger's avatar
Sascha Herzinger committed
121
122
123
124
        results: {
          data: [],
          statistics: {}
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
125
126
127
128
129
      }
    },
    computed: {
      args () {
        return {
130
131
          variables: this.numData,
          categories: this.catData,
132
          id_filter: [],
Sascha Herzinger's avatar
Sascha Herzinger committed
133
134
135
136
137
138
139
          subsets: store.getters.subsets
        }
      },
      validArgs () {
        return this.numData.length > 0
      },
      margin () {
140
        const left = 60
Sascha Herzinger's avatar
Sascha Herzinger committed
141
        const top = 10
Sascha Herzinger's avatar
Sascha Herzinger committed
142
143
        const right = 50
        const bottom = this.height * 0.1
Sascha Herzinger's avatar
Sascha Herzinger committed
144
145
146
147
148
149
150
        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 }
      },
151
152
153
154
155
156
157
158
159
160
161
      points () {
        const points = {}
        Object.keys(this.results.statistics).forEach(label => {
          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)
            .map(d => d[variable])
        })
        return points
      },
162
163
164
      numOfBoxplots () {
        return Object.keys(this.results.statistics).length
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
165
      boxplotWidth () {
166
        const maxBoxplotWidth = this.padded.width / 4
167
        const minBoxplotWidth = 10
168
169
        let boxplotWidth = this.padded.width / this.numOfBoxplots - this.padded.width * 0.05
        boxplotWidth = boxplotWidth > maxBoxplotWidth ? maxBoxplotWidth : boxplotWidth
170
        boxplotWidth = boxplotWidth < minBoxplotWidth ? minBoxplotWidth : boxplotWidth
171
172
173
174
175
176
        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
177
        const padding = (extent[1] - extent[0]) / 20
Sascha Herzinger's avatar
Sascha Herzinger committed
178
179
        const x = d3.scalePoint()
          .domain(Object.keys(this.results.statistics))
Sascha Herzinger's avatar
Sascha Herzinger committed
180
          .range([0, this.padded.width])
181
          .padding(0.5)
182
        const y = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
183
          .domain([extent[0] - padding, extent[1] + padding])
Sascha Herzinger's avatar
Sascha Herzinger committed
184
          .range([this.padded.height, 0])
Sascha Herzinger's avatar
Sascha Herzinger committed
185
186
187
        return { x, y }
      },
      axis () {
Sascha Herzinger's avatar
Sascha Herzinger committed
188
        const x = d3.axisBottom(this.scales.x).tickFormat(d => utils.truncate({fullStr: d, strLen: 35}))
Sascha Herzinger's avatar
Sascha Herzinger committed
189
        const y = d3.axisLeft(this.scales.y)
190
        return { x, y }
Sascha Herzinger's avatar
Sascha Herzinger committed
191
192
      }
    },
193
194
195
    // 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
196
197
198
199
200
201
202
203
204
205
    watch: {
      '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
206
207
208
      },
      'axis': {
        handler: function (newAxis) {
209
210
211
212
213
214
215
216
217
          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)
          })
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
218
219
220
      }
    },
    methods: {
221
      showTooltip (label) {
222
223
224
225
        // https://github.com/atomiks/tippyjs/issues/74
        Object.keys(this.tooltips).forEach(label => this.tooltips[label].forEach(d => d.tip.destroyAll()))
        this.tooltips = {}

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
        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`)
        this.tooltips[label] = [
          { 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 },
          { tip: tippy(median, Object.assign({position: 'right'}, defaultOptions)), el: median }
        ]
        this.tooltips[label].forEach(d => {
          d.tip.show(d.tip.getPopperElement(d.el))
        })
      },
      hideTooltip (label) {
        this.tooltips[label].forEach(d => d.tip.hide(d.tip.getPopperElement(d.el)))
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
      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
272
            this.handleResize()
Sascha Herzinger's avatar
Sascha Herzinger committed
273
274
275
276
277
278
279
280
281
          })
          .catch(error => console.error(error))
      }
    },
    components: {
      DataBox,
      TaskView
    },
    mixins: [
282
      requestHandling
Sascha Herzinger's avatar
Sascha Herzinger committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    ],
    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
314
315
      .fjs-tooltip
        position: absolute
Sascha Herzinger's avatar
Sascha Herzinger committed
316
317
      svg
        flex: 1
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
        .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
333
        .fjs-points
Sascha Herzinger's avatar
Sascha Herzinger committed
334
335
336
337
338
</style>


<!--CSS for dynamically created components-->
<style lang="sass">
339
  .fjs-boxplot-axis
Sascha Herzinger's avatar
Sascha Herzinger committed
340
341
342
343
    shape-rendering: crispEdges
    stroke-width: 2px
    .tick
      shape-rendering: crispEdges
Sascha Herzinger's avatar
Sascha Herzinger committed
344
345
      text
        font-size: 18px
Sascha Herzinger's avatar
Sascha Herzinger committed
346
347
    line
      stroke: #999
Sascha Herzinger's avatar
Sascha Herzinger committed
348
349
350
351
  .fjs-x-axis
    .tick
      text
        text-anchor: start
Sascha Herzinger's avatar
Sascha Herzinger committed
352
        font-size: 14px
Sascha Herzinger's avatar
Sascha Herzinger committed
353
</style>