-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathbar_chart.js
109 lines (96 loc) · 2.94 KB
/
bar_chart.js
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
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
const d3 = Object.assign({},
require('d3-scale'),
require('d3-axis'),
require('d3-array')
);
class BarChart {
constructor({ data, width, height, xAxisLabel, yAxisLabel, containerId }) {
this.data = data;
this.width = width;
this.height = height;
this.xAxisLabel = xAxisLabel;
this.yAxisLabel = yAxisLabel;
this.containerId = containerId;
this.axisLabelMargin = 10;
this.margin = {
top: 10,
right: 10,
bottom: 34,
left: 34
};
}
render(container) {
const {
data,
width,
height,
xAxisLabel,
yAxisLabel,
axisLabelMargin,
margin
} = this;
const xScale = d3.scaleBand()
.domain(this.data.map(({ name }) => name))
.rangeRound([0, width - axisLabelMargin - margin.left - margin.right])
.padding(0.25);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, ({ count }) => count) + 10])
.range([height - axisLabelMargin - margin.top - margin.bottom, 0]);
const xAxis = d3.axisBottom()
.scale(xScale)
.tickSizeInner(0)
.tickSizeOuter(0);
const yAxis = d3.axisLeft()
.tickSizeInner(0)
.tickSizeOuter(0)
.scale(yScale);
const g = container.append('svg')
.attr('class', 'svg-chart')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
g.append('rect')
.attr('class', 'background')
.attr('x', axisLabelMargin)
.attr('width', width - axisLabelMargin - margin.left - margin.right)
.attr('height', height - margin.top - margin.bottom - axisLabelMargin);
g.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(' + axisLabelMargin + ',' +
(height - axisLabelMargin - margin.top - margin.bottom) + ')')
.call(xAxis)
.append('text')
.attr('class', 'axis-label')
.attr('x', (width - margin.left - margin.right - axisLabelMargin) / 2)
.attr('y', margin.left)
.style('text-anchor', 'middle')
.text(xAxisLabel);
g.append('g')
.attr('class', 'y axis')
.attr('transform', 'translate(' + axisLabelMargin + ', 0)')
.call(yAxis)
.append('text')
.attr('class', 'axis-label')
.attr('transform', 'rotate(-90)')
.attr('y', -margin.left)
.attr('x', -(height - margin.top - margin.bottom - axisLabelMargin) / 2)
.style('text-anchor', 'middle')
.text(yAxisLabel);
g.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', function(d) {
return xScale(d.name) + axisLabelMargin;
})
.attr('y', function(d) {
return yScale(d.count);
})
.attr('width', xScale.bandwidth())
.attr('height', function(d) {
return height - margin.top - margin.bottom - yScale(d.count) - axisLabelMargin;
});
}
}
module.exports = BarChart;