# Stacked Bar Chart
Original D3 demo at https://bl.ocks.org/mbostock/3886208
<template>
<d3-cartesian class="demo" :margin="margin" :width="860" :height="450" :x="x" :y="y">
<template #default="props">
<d3-stacked-bars :data="data" x="State" :keys="keys" :colorFn="colorFn" v-bind="props"/>
<d3-legend class="legend" :data="legendItems" label="name" color="color" align="right" :x="800"/>
</template>
<template #south="props">
<d3-axis orientation="Bottom" v-bind="props"/>
</template>
<template #west="props">
<d3-axis orientation="Left" :config="configY" v-bind="props"/>
</template>
</d3-cartesian>
</template>
<script>
import * as d3 from 'd3'
export default {
data () {
return {
margin: { top: 20, right: 10, bottom: 30, left: 30 },
x: { type: 'Band', domain: [], config: scale => scale.paddingInner(0.05) },
y: { type: 'Linear', domain: [0, 1] },
data: [],
keys: [],
configY: axis => axis.ticks(null, 's')
}
},
computed: {
colorFn () {
return d3.scaleOrdinal().domain(this.keys)
.range(['#98abc5', '#8a89a6', '#7b6888', '#6b486b', '#a05d56', '#d0743c', '#ff8c00'])
},
legendItems () {
return this.keys.map(k => {
return { name: k, color: this.colorFn(k) }
}).reverse()
}
},
created () {
d3.csv('/data/state-population.csv',
(d, index, columns) => {
let i, t
for (i = 1, t = 0; i < columns.length; ++i) {
t += d[columns[i]] = +d[columns[i]]
}
d.total = t
return d
}).then(data => {
data.sort((a, b) => b.total - a.total)
this.x.domain = data.map(d => d.State)
this.y.domain = [0, d3.max(data, d => d.total)]
this.data = data
this.keys = data.columns.slice(1)
})
}
}
</script>
<style lang="scss" scoped>
.demo /deep/ {
.legend {
font-size: 11px;
font-family: sans-serif;
}
.axis path {
display: none;
}
}
</style>
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
45
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
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
45
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