-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sugars.html
81 lines (71 loc) · 2.16 KB
/
Sugars.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> Cereal Manufacturers Analysis </title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body onload='init()'>
<h1> Statistics about Cereal Manufacturers! </h1>
<svg width="600" height="500"></svg>
<script>
//setting initial vars
var svg = d3.select("svg")
var margin = 150
var width = svg.attr("width") - margin
var height = svg.attr("height") - margin;
//setting x and y axis scales
var x = d3.scaleBand().range ([0, width]).padding(0.4)
var y = d3.scaleLinear().range ([height, 0]);
//initializing group element
var g = svg.append("g")
.attr("transform", "translate(" + 100 + "," + 100 + ")");
//loading data and appending axis
async function init() {
const data = await d3.csv('cereal.csv');
console.log(data)
//setting axis domains based on data
x.domain(data.map(function(d) { return d.mfr; }));
y.domain([0, 16]);
//appending the x axis
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.append("text")
.attr("x", width - 200)
.attr("y", 30)
.attr("text-anchor", "end")
.attr("stroke", "black")
.text("Manufacturer");
//appending the y axis
g.append("g")
.call(d3.axisLeft(y).tickFormat(function(d){
return d;
}).ticks(10))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", "-5.1em")
.attr("text-anchor","end")
.attr("stroke", "black")
.text("Rating");
//adding the bars
g.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.mfr); })
.attr("y", function(d) { return y(d.sugars); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.sugars); });
//adding text element
svg.append("text")
.attr("transform", "translate(100,0)")
.attr("x",50)
.attr("y",50)
.attr("font-size", "20px")
.text("Manufacturer vs Avg Sugars")
};
</script>
</body>
</html>