-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rating.html
84 lines (73 loc) · 2.29 KB
/
Rating.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
<!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, d3.max(data, function(d) { return d.rating; })]);
//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");
var sum = d3.sum(data, function(d) { return d.rating; });
var avg = sum/data.length;
//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.rating); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.rating); });
//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 Rating")
};
</script>
</body>
</html>