-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.html
120 lines (104 loc) · 2.63 KB
/
example.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
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
110
111
112
113
114
115
116
117
118
119
120
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bar Chart Example</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 11px;
}
ul {
margin: 0;
padding: 0 0 0 20px;
}
li {
display: inline;
list-style: none;
}
a {
font-size: 12px;
background: #ccc;
border-radius: 12px;
padding: 3px 8px;
border: 1px solid #eee;
cursor: pointer;
}
</style>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<div></div>
<ul>
<li><a onclick="update([0.4,0.1,0.5]);">Update with [0.4,0.1,0.5]</a></li>
<li><a onclick="update([0.2,0.6,0.3,0.1,0.7]);">Update with [0.2,0.6,0.3,0.1,0.7]</a></li>
<li><a onclick="update([0.2,0.4,0.3,0.6]);">Reset</a></li>
</ul>
<script type="text/javascript">
var svg = d3.select("div").append("svg")
.attr("width", 800)
.attr("height", 220);
var data = [0.2,0.4,0.3,0.6];
var node;
var scale = d3.scale.linear()
.domain([0,1])
.range([0,800]);
var color = d3.scale.category20c();
// functions to calculate y positions
var y_rect = function(d,i) { return i*40+16; };
var y_text = function(d,i) { return i*40+30; };
function update(data)
{
// initial select, like all D3 examples, bind it to data
node = svg.selectAll(".node")
.data(data, String)
// update changing elements with new percentage and bar width
node.each(function(d, i) {
single = d3.select(this)
single.selectAll("rect")
.transition()
.attr("width", scale)
.attr("y", y_rect(d,i))
.duration(300)
single.selectAll("text")
.transition()
.attr("y", y_text(d,i))
.text(function() { return Math.round(d*100) + "%"; })
.duration(300)
})
// Create entering nodes with the bar (<rect>) and the percentage (<text>)
// grouped in a <g class="node"> element
var enter = node.enter().append("g")
.attr("class", "node")
enter.append("rect")
.attr("width", scale)
.attr("height", 20)
.attr("x", 20)
.attr("y", y_rect)
.style("fill", color)
.attr("rx", "5px")
.attr("ry", "5px")
enter.append("text")
.text(function(d,i) { return Math.round(d*100) + "%"; })
.style("fill", "#000")
.attr("x", function(d,i) { return scale(d)-8; })
.attr("y", y_text)
.style("text-anchor", "right")
// Add a fade in transition to all entering elements and child elements
enter.selectAll("*")
.style("opacity", 0)
.transition()
.duration(300)
.style("opacity", 1)
// fade out and remove all exiting elements
node.exit()
.style("opacity", 1)
.transition()
.duration(300)
.style("opacity", 0)
.remove()
}
update(data);
</script>
</body>
</html>