-
Notifications
You must be signed in to change notification settings - Fork 221
/
barchart.html
81 lines (71 loc) · 3.07 KB
/
barchart.html
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
<!DOCTYPE html>
<html>
<head>
<title>BarChart! </title>
<script src="../js/d3.min.js"></script>
</head>
<body>
<svg width="1600" height="800" id="mainsvg" class="svgs"></svg>
<script>
const data = [{name: 'Shao-Kui', value:6},
{name:'Wen-Yang', value:6}, {name:'Cai Yun', value:16}, {name:'Liang Yuan', value: 10},
{name:'Yuan-Chen', value:6}, {name:'Rui-Long', value:10}, {name:'Dong Xin', value:12},
{name:'He Yu', value:20}, {name:'Xiang-Li', value:12}, {name:'Godness', value:20},
{name:'Wei-Yu', value:15}, {name:'Chen Zheng', value:14},
{name:'Yu Peng', value:15}, {name:'Li Jian', value:18}];
const svg = d3.select('#mainsvg');
const width = +svg.attr('width');
const height = +svg.attr('height');
const margin = {top: 60, right: 30, bottom: 60, left: 150};
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
const g = svg.append('g').attr('id', 'maingroup')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
const xScale = d3.scaleLinear().
domain([0, d3.max(data, datum=>datum.value)]).
range([0, innerWidth]);
const yScale = d3.scaleBand().
domain(data.map(datum => datum.name)).
range([0, innerHeight])
.padding(0.1);
data.forEach(datum => {
g.append('rect')
.attr('width', xScale(datum.value))
.attr('height', yScale.bandwidth())
.attr('y', yScale(datum.name))
.attr('fill', 'green')
.attr('opacity', '0.8')
})
// the following four lines of code is the simplest pattern of adding axis;
const yAxis = d3.axisLeft(yScale);
const xAxis = d3.axisBottom(xScale);
g.append('g').call(yAxis);
g.append('g').call(xAxis).attr('transform', `translate(0, ${innerHeight})`);
// the following lines are improved version of the above four lines,
// which configurates more attributes and adds two axis labels;
/*const yAxis = d3.axisLeft(yScale).tickSize(-innerWidth);
const xAxis = d3.axisBottom(xScale).tickSize(-innerHeight);
const yAxisGroup = g.append('g').call(yAxis)
.attr('id', 'yaxis')
.append('text')
.text('Name')
.attr('font-size', '3em')
.attr('transform', 'rotate(-90)') // y-axis label needs an additional transform;
.attr('x', -innerHeight / 2)
.attr('y', -120)
.attr('fill', 'black')
const xAxisGroup = g.append('g').call(xAxis)
.attr('id', 'xaxis')
.attr('transform', `translate(${0}, ${innerHeight})`)
.append('text')
.text('Value')
.attr('font-size', '3em')
.attr('x', innerWidth / 2)
.attr('y', 50)
.attr('fill', 'black');*/
d3.selectAll('.tick text').attr('font-size', '2em');
g.append('text').text('Members of CSCG').attr('font-size', '3em')
.attr('x', innerWidth / 2 - 200).attr('y', -10)
</script>
</body>
</html>