Blame view

flaskr/static/js/plots/emissions-per-distance.js 11.5 KB
910464a0   Antoine Goutenoir   feat: switch to d...
1
2
3
// export draw_emissions_per_distance

function draw_emissions_per_distance(divId, csvUrl) {
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
4
    // let divId = "emissions_per_distance_histogram";
910464a0   Antoine Goutenoir   feat: switch to d...
5

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
6
7
8
9
    // set the dimensions and margins of the graph
    let margin = {top: 30, right: 62, bottom: 62, left: 72},
        width = 960 - margin.left - margin.right,
        height = 540 - margin.top - margin.bottom;
910464a0   Antoine Goutenoir   feat: switch to d...
10

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
11
12
13
14
    function getTicks(maxValue, interval, startValue = 0) {
        let range = [];
        for (let i = startValue; i <= maxValue; i += interval) {
            range.push(i);
910464a0   Antoine Goutenoir   feat: switch to d...
15
        }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
16
17
        return range;
    }
910464a0   Antoine Goutenoir   feat: switch to d...
18

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
19
20
21
22
23
    function getBottomTicks(maxDistance) {
        let range = getTicks(maxDistance, 2500, 2500);
        range.push(500);
        return range;
    }
910464a0   Antoine Goutenoir   feat: switch to d...
24

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
25
26
27
    function getLeftTicks(maxemissions) {
        return getTicks(maxemissions, Math.floor((maxemissions / 8) / 1000) * 1000);
    }
910464a0   Antoine Goutenoir   feat: switch to d...
28

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
29
30
31
32
33
34
35
36
37
38
39
    function getRightTicks(maxemissionsPercent) {
        return getTicks(maxemissionsPercent, 2);
    }

    function getAttendeeOnRight(sliceId, attendeeNumberPerGroup) {
        let attendeeSum = 0;
        let sliceInt = Math.floor(sliceId);
        let sliceFloat = sliceId - sliceInt;
        for (let i = sliceInt; i < attendeeNumberPerGroup.length; i++) {
            attendeeSum += attendeeNumberPerGroup[i] * (1 - sliceFloat);
            sliceFloat = 0;
910464a0   Antoine Goutenoir   feat: switch to d...
40
        }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
41
        return attendeeSum;
910464a0   Antoine Goutenoir   feat: switch to d...
42

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
43
    }
910464a0   Antoine Goutenoir   feat: switch to d...
44

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    function setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, box, vertical, rightArea) {
        // mousex = d3.mouse(this);
        // const x = d3.mouse(this)[0];
        // const y = d3.mouse(this)[1];
        const x = d3.pointer(event)[0];
        const y = d3.pointer(event)[1];
        // var y = d3.event.pageY - document.getElementById(<id-of-your-svg>).getBoundingClientRect().y + 10
        // x += 5;
        vertical.style("left", x + "px");
        rightArea.style("left", x + "px");
        box.style("left", (x + 10) + "px");
        box.style("top", (y - 20) + "px");
        let sliceId = xScale.invert(x - d3.selectAll("g.yl.axis")._groups[0][0].getBoundingClientRect().right) / 500;
        // let sliceId = xScale.invert(x * 1.025 - d3.selectAll("g.yl.axis")._groups[0][0].getBoundingClientRect().x- margin.left)/500 +1;
        let attendeePercent = (getAttendeeOnRight(sliceId, attendeeNumberPerGroup) / attendeeSum * 100.0).toFixed(1);
        if (x > d3.selectAll("g.yr.axis")._groups[0][0].getBoundingClientRect().x ||
            x < d3.selectAll("g.yl.axis")._groups[0][0].getBoundingClientRect().right) {
            rightArea.style("width", 0);
            vertical.style("width", 0);
            box.style("display", "none");
910464a0   Antoine Goutenoir   feat: switch to d...
65
        }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
66
67
68
69
        else {
            rightArea.style("width", d3.selectAll("g.yr.axis")._groups[0][0].getBoundingClientRect().x - x);
            vertical.style("width", "2px");
            box.style("display", "inherit");
910464a0   Antoine Goutenoir   feat: switch to d...
70
        }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
71
72
73
74
75
        box.text(attendeePercent + " % of attendees");
        box.text(attendeePercent + " % of attendees");
        // console.log(d3.selectAll("g.x.axis")._groups[0][0]);
        // console.log(d3.selectAll("g.x.axis")._groups[0][0].getBoundingClientRect().x);
    }
910464a0   Antoine Goutenoir   feat: switch to d...
76

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
77
78
79
80
81
82
83
84
85
86
87
88
    function addVerticalLineAndListenCursor(xScale, attendeeNumberPerGroup, attendeeSum) {
        let vertical = d3.select("#" + divId)
            .append("div")
            .attr("class", "remove")
            .style("position", "absolute")
            .style("z-index", "19")
            .style("width", "2px")
            .style("height", (height) + "px")
            .style("top", (10 + margin.top) + "px")
            .style("bottom", "30px")
            .style("left", "0px")
            .style("background", "#000");
910464a0   Antoine Goutenoir   feat: switch to d...
89

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
90
91
92
93
94
95
96
97
98
99
100
        let rightArea = d3.select("#" + divId)
            .append("div")
            .attr("class", "remove")
            .style("position", "absolute")
            .style("z-index", "-50")
            .style("width", "2000px")
            .style("height", (height) + "px")
            .style("top", (10 + margin.top) + "px")
            .style("bottom", "30px")
            .style("left", "0px")
            .style("background", "rgba(60, 200, 60, 0.3)");
910464a0   Antoine Goutenoir   feat: switch to d...
101
102


ad528ad0   Antoine Goutenoir   fix: use DOMConte...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        let box = d3.select("#" + divId)
            .append("div")
            .attr("class", "remove")
            .style("position", "absolute")
            .style("z-index", "20")
            .style("width", "150px")
            .style("height", "22px")
            .style("top", "10px")
            .style("bottom", "30px")
            .style("left", "0px")
            .style("border", "1px solid grey")
            .style("background", "rgba(255, 255, 255, 0.7)");
        d3.select("#" + divId)
            .on("mousemove", function (event) {
                setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, box, vertical, rightArea);
            })
            .on("mouseover", function (event) {
                setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, box, vertical, rightArea);
910464a0   Antoine Goutenoir   feat: switch to d...
121

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
122
123
            });
    }
910464a0   Antoine Goutenoir   feat: switch to d...
124

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
125
126
127
128
129
130
131
132
133
134
135
136
    document.addEventListener("DOMContentLoaded", () => {
        let maxemissions = 0;
        let maxemissionsPercent = 0;
        let maxDistance = 0;
        let svg = d3.select("#" + divId)
            .append("svg")
            .attr("id", divId + "-svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");
910464a0   Antoine Goutenoir   feat: switch to d...
137

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
138
139
140
141
142
        let emissionsPerGroup = [];
        let attendeeNumberPerGroup = [];
        let emissionsSum = 0;
        let attendeeSum = 0;
        let rows = [];
910464a0   Antoine Goutenoir   feat: switch to d...
143

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        const on_csv_datum = function (datum) {
            let trainAttendee = parseInt(datum["train trips_amount"]);
            let planeAttendee = parseInt(datum["plane trips_amount"]);
            if (trainAttendee === 0 && planeAttendee === 0) {
                return;
            }
            let attendeeNumber = trainAttendee + planeAttendee;
            let distance_km = datum.distance_km / attendeeNumber;
            let co2_kg = parseFloat(datum.co2_kg);
            if (co2_kg === "NaN" || distance_km / 500 > 37 || distance_km === "NaN") {
                return;
            }
            rows.push(datum);
            maxDistance = Math.max(maxDistance, distance_km);
            emissionsSum += co2_kg;
910464a0   Antoine Goutenoir   feat: switch to d...
159

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
160
        };
910464a0   Antoine Goutenoir   feat: switch to d...
161

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        const on_csv_ready = function () {
            for (let i = 0; i <= maxDistance / 500; i++) {
                emissionsPerGroup[i] = 0;
                attendeeNumberPerGroup[i] = 0;
            }
            rows.forEach((element, index) => {
                let trainAttendee = parseInt(element["train trips_amount"]);
                let planeAttendee = parseInt(element["plane trips_amount"]);
                let attendeeNumber = trainAttendee + planeAttendee;
                let distance_km = element.distance_km / attendeeNumber;
                let co2_kg = parseFloat(element.co2_kg);
                emissionsPerGroup[Math.floor(distance_km / 500)] += parseFloat(co2_kg);
                attendeeNumberPerGroup[Math.floor(distance_km / 500)] += attendeeNumber;
                attendeeSum += attendeeNumber;
            });
            emissionsPerGroup.forEach((element, index) => {
                maxemissions = Math.max(maxemissions, element);
                maxemissionsPercent = Math.max(maxemissionsPercent, element / emissionsSum * 100.0)
            });
            maxDistance += 2000;
            // console.log(maxDistance);
910464a0   Antoine Goutenoir   feat: switch to d...
183

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
184
185
186
187
188
189
190
191
            //Title
            svg.append("text")
                .attr("transform",
                    "translate(" + (70 + margin.left) + ", -12)")
                .style("text-anchor", "middle")
                .style("font-weight", "bold")
                .style("font-size", "130%")
                .text("Emissions per distance");
910464a0   Antoine Goutenoir   feat: switch to d...
192

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
            // X axis: scale and draw:
            let x = d3.scaleLinear()
                .domain([0, maxDistance])
                .range([0, width]);
            let xAxis = d3.axisBottom(x)
                .tickValues(getBottomTicks(maxDistance));
            svg.append("g")
                .attr("transform", "translate(0," + height + ")")
                .attr("class", "x axis")
                .call(xAxis);
            d3.selectAll("g.x.axis")
                .selectAll(".tick")
                .filter(function (d) {
                    return d === 0;
                })
                .remove();
910464a0   Antoine Goutenoir   feat: switch to d...
209

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
210
211
212
213
214
215
216
217
218
            // Y axis Left
            let yl = d3.scaleLinear()
                .domain([0, maxemissions])
                .range([height, 0]);
            let ylAxis = d3.axisLeft(yl)
                .tickValues(getLeftTicks(maxemissions));
            svg.append("g")
                .attr("class", "yl axis")
                .call(ylAxis);
910464a0   Antoine Goutenoir   feat: switch to d...
219

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
220
221
222
223
224
225
226
227
228
229
            // Y axis Right
            let yr = d3.scaleLinear()
                .domain([0, maxemissionsPercent])
                .range([height, 0]);
            let yrAxis = d3.axisRight(yr)
                .tickValues(getRightTicks(maxemissionsPercent));
            svg.append("g")
                .attr("transform", "translate(" + width + ", 0)")
                .attr("class", "yr axis")
                .call(yrAxis);
910464a0   Antoine Goutenoir   feat: switch to d...
230

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
231
232
233
234
235
236
            svg.append("text")
                .attr("transform",
                    "translate(" + (width / 2) + " ," +
                    (height + margin.top + 12) + ")")
                .style("text-anchor", "middle")
                .text("Distance travelled (km)");
910464a0   Antoine Goutenoir   feat: switch to d...
237

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
238
239
240
241
242
243
244
            svg.append("text")
                .attr("transform",
                    "translate(" + (width) + ", 0), rotate(-90)")
                .attr("x", 0 - (height / 2))
                .attr("y", 42)
                .style("text-anchor", "middle")
                .text("Share of emission [%]");
910464a0   Antoine Goutenoir   feat: switch to d...
245

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
246
247
248
249
250
251
252
253
254
255
256
            svg.append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 0 - margin.left)
                .attr("x", 0 - (height / 2))
                .attr("dy", "1em")
                .style("text-anchor", "middle")
                .text("Emission (tCO2e)");
            // set the parameters for the histogram
            var histogram = d3.histogram()
                .domain(x.domain())  // then the domain of the graphic
                .thresholds(x.ticks(Math.floor(maxDistance / 500))); // then the numbers of bins
910464a0   Antoine Goutenoir   feat: switch to d...
257

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
            let histolol = histogram(0);
            // console.log(histolol);
            let barSettings = [];
            emissionsPerGroup.forEach((element, index) => {
                barSettings[index] =
                    {
                        height: element,
                        leftBorder: histolol[index].x0,
                        rightBorder: histolol[index].x1,
                    };
                // console.log(index);
                // console.log(barSettings[index]);
            });
            svg.selectAll("rect")
                .data(barSettings)
                .enter()
                .append("rect")
                .attr("x", 1)
                .attr("transform", function (d) {
                    return "translate(" + x(d.leftBorder) + "," + yl(d.height) + ")";
                })
                .attr("width", function (d) {
                    return x(d.rightBorder) - x(d.leftBorder) - 1;
                })
                .attr("height", function (d) {
                    return (height - yl(d.height));
                })
                .style("z-index", "500")
                .style("fill", "#4444E5");
            addVerticalLineAndListenCursor(x, attendeeNumberPerGroup, attendeeSum);
910464a0   Antoine Goutenoir   feat: switch to d...
288
289
        };

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
290
291
292
        d3.csv(csvUrl, on_csv_datum)
            .then(on_csv_ready);
    });
11ab5596   Adrenesis   Add emission-per-...
293

910464a0   Antoine Goutenoir   feat: switch to d...
294
}