Blame view

flaskr/static/js/plots/emissions-per-distance.js 12.4 KB
701dbf83   Antoine Goutenoir   feat: integrate t...
1
function draw_emissions_per_distance(containerSelector, csvUrl) {
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
2
    // set the dimensions and margins of the graph
79eadc9f   Antoine Goutenoir   feat: polish
3
    let margin = {top: 48, right: 88, bottom: 68, left: 98},
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
4
5
        width = 960 - margin.left - margin.right,
        height = 540 - margin.top - margin.bottom;
910464a0   Antoine Goutenoir   feat: switch to d...
6

8daea46b   Antoine Goutenoir   fix: interactive ...
7
8
9
    const sliceThickness = 500.0;


ad528ad0   Antoine Goutenoir   fix: use DOMConte...
10
11
12
13
    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...
14
        }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
15
16
        return range;
    }
910464a0   Antoine Goutenoir   feat: switch to d...
17

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

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

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
28
29
30
31
    function getRightTicks(maxemissionsPercent) {
        return getTicks(maxemissionsPercent, 2);
    }

8daea46b   Antoine Goutenoir   fix: interactive ...
32
33
    function getAttendeesAmountOnRight(sliceId, attendeeNumberPerGroup) {
        let attendeesAmount = 0;
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
34
35
36
        let sliceInt = Math.floor(sliceId);
        let sliceFloat = sliceId - sliceInt;
        for (let i = sliceInt; i < attendeeNumberPerGroup.length; i++) {
8daea46b   Antoine Goutenoir   fix: interactive ...
37
            attendeesAmount += attendeeNumberPerGroup[i] * (1 - sliceFloat);
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
38
            sliceFloat = 0;
910464a0   Antoine Goutenoir   feat: switch to d...
39
        }
8daea46b   Antoine Goutenoir   fix: interactive ...
40
        return attendeesAmount;
910464a0   Antoine Goutenoir   feat: switch to d...
41

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

8daea46b   Antoine Goutenoir   fix: interactive ...
44
    function setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, tooltip, vertical, rightArea) {
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
45
46
47
        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
8daea46b   Antoine Goutenoir   fix: interactive ...
48
49
        // console.log("Mouse move", x, y);

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
50
51
        vertical.style("left", x + "px");
        rightArea.style("left", x + "px");
990a9752   Antoine Goutenoir   feat: clean the h...
52
        rightArea.style("width", (width + margin.left - x) + "px");
8daea46b   Antoine Goutenoir   fix: interactive ...
53
54
55
        tooltip.style("left", (x + 10) + "px");
        tooltip.style("top", (y - 20) + "px");

8daea46b   Antoine Goutenoir   fix: interactive ...
56
        let sliceId = xScale.invert(x - margin.left) / sliceThickness;
79eadc9f   Antoine Goutenoir   feat: polish
57
        // console.log(`Slice ${sliceId} under the mouse.`);
8daea46b   Antoine Goutenoir   fix: interactive ...
58

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
59
        // let sliceId = xScale.invert(x * 1.025 - d3.selectAll("g.yl.axis")._groups[0][0].getBoundingClientRect().x- margin.left)/500 +1;
8daea46b   Antoine Goutenoir   fix: interactive ...
60
61
62
63
64
        let attendeePercent = (getAttendeesAmountOnRight(sliceId, attendeeNumberPerGroup) / attendeeSum * 100.0).toFixed(1);
        if (
            x < margin.left
            ||
            x > width + margin.left
79eadc9f   Antoine Goutenoir   feat: polish
65
66
67
68
            ||
            y < margin.top
            ||
            y > height + margin.top
8daea46b   Antoine Goutenoir   fix: interactive ...
69
        ) {
e86f2462   Antoine Goutenoir   design: refactor ...
70
71
            rightArea.style("display", "none");
            vertical.style("display", "none");
8daea46b   Antoine Goutenoir   fix: interactive ...
72
            tooltip.style("display", "none");
e86f2462   Antoine Goutenoir   design: refactor ...
73
74
75
        } else {
            rightArea.style("display", "inherit");
            vertical.style("display", "inherit");
8daea46b   Antoine Goutenoir   fix: interactive ...
76
            tooltip.style("display", "inherit");
910464a0   Antoine Goutenoir   feat: switch to d...
77
        }
701dbf83   Antoine Goutenoir   feat: integrate t...
78

990a9752   Antoine Goutenoir   feat: clean the h...
79
        tooltip.text((((attendeePercent < 10) ? '0' : '') + attendeePercent) + "% of attendees");
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
80
    }
910464a0   Antoine Goutenoir   feat: switch to d...
81

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
82
    function addVerticalLineAndListenCursor(xScale, attendeeNumberPerGroup, attendeeSum) {
701dbf83   Antoine Goutenoir   feat: integrate t...
83
        let verticalRuler = d3.select(containerSelector)
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
84
            .append("div")
701dbf83   Antoine Goutenoir   feat: integrate t...
85
            .attr("class", "no-pointer-events")
e86f2462   Antoine Goutenoir   design: refactor ...
86
            .style("display", "none")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
87
88
89
90
            .style("position", "absolute")
            .style("z-index", "19")
            .style("width", "2px")
            .style("height", (height) + "px")
79eadc9f   Antoine Goutenoir   feat: polish
91
            .style("top", (margin.top) + "px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
92
            .style("bottom", "30px")
8daea46b   Antoine Goutenoir   fix: interactive ...
93
            .style("left", "-10px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
94
            .style("background", "#000");
910464a0   Antoine Goutenoir   feat: switch to d...
95

701dbf83   Antoine Goutenoir   feat: integrate t...
96
        let rightArea = d3.select(containerSelector)
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
97
            .append("div")
701dbf83   Antoine Goutenoir   feat: integrate t...
98
            .attr("class", "no-pointer-events")
e86f2462   Antoine Goutenoir   design: refactor ...
99
            .style("display", "none")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
100
101
            .style("position", "absolute")
            .style("z-index", "-50")
8daea46b   Antoine Goutenoir   fix: interactive ...
102
            .style("width", "0px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
103
            .style("height", (height) + "px")
79eadc9f   Antoine Goutenoir   feat: polish
104
            .style("top", (margin.top) + "px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
105
106
107
            .style("bottom", "30px")
            .style("left", "0px")
            .style("background", "rgba(60, 200, 60, 0.3)");
910464a0   Antoine Goutenoir   feat: switch to d...
108

701dbf83   Antoine Goutenoir   feat: integrate t...
109
        let tooltip = d3.select(containerSelector)
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
110
            .append("div")
8daea46b   Antoine Goutenoir   fix: interactive ...
111
112
            .attr("class", "no-pointer-events")
            .style("display", "none")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
113
114
            .style("position", "absolute")
            .style("z-index", "20")
701dbf83   Antoine Goutenoir   feat: integrate t...
115
            .style("width", "161px")
e86f2462   Antoine Goutenoir   design: refactor ...
116
            .style("height", "35px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
117
118
119
            .style("top", "10px")
            .style("bottom", "30px")
            .style("left", "0px")
e86f2462   Antoine Goutenoir   design: refactor ...
120
121
122
123
            .style("padding-left", "10px")
            .style("padding-right", "0px")
            .style("padding-top", "6px")
            .style("padding-bottom", "6px")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
124
125
            .style("border", "1px solid grey")
            .style("background", "rgba(255, 255, 255, 0.7)");
561e9392   Antoine Goutenoir   chore: lint
126

701dbf83   Antoine Goutenoir   feat: integrate t...
127
        d3.select(containerSelector + " svg")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
128
            .on("mousemove", function (event) {
8daea46b   Antoine Goutenoir   fix: interactive ...
129
                setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, tooltip, verticalRuler, rightArea);
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
130
131
            })
            .on("mouseover", function (event) {
8daea46b   Antoine Goutenoir   fix: interactive ...
132
                setupCursorBoxes(event, attendeeSum, attendeeNumberPerGroup, xScale, tooltip, verticalRuler, rightArea);
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
133
134
            });
    }
910464a0   Antoine Goutenoir   feat: switch to d...
135

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
136
    document.addEventListener("DOMContentLoaded", () => {
701dbf83   Antoine Goutenoir   feat: integrate t...
137
138
        width = Math.max(880, $(containerSelector).parent().width());
        width = width - margin.left - margin.right;
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
139
140
141
        let maxemissions = 0;
        let maxemissionsPercent = 0;
        let maxDistance = 0;
701dbf83   Antoine Goutenoir   feat: integrate t...
142
        let svg = d3.select(containerSelector)
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
143
            .append("svg")
701dbf83   Antoine Goutenoir   feat: integrate t...
144
            // .attr("id", containerSelector + "-svg")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
145
146
147
148
149
            .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...
150

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
151
152
153
154
155
        let emissionsPerGroup = [];
        let attendeeNumberPerGroup = [];
        let emissionsSum = 0;
        let attendeeSum = 0;
        let rows = [];
910464a0   Antoine Goutenoir   feat: switch to d...
156

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
157
158
159
160
161
162
163
164
165
        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);
e86f2462   Antoine Goutenoir   design: refactor ...
166
            if (co2_kg === "NaN" || distance_km / sliceThickness > 37 || distance_km === "NaN") {
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
167
168
169
170
171
                return;
            }
            rows.push(datum);
            maxDistance = Math.max(maxDistance, distance_km);
            emissionsSum += co2_kg;
910464a0   Antoine Goutenoir   feat: switch to d...
172

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

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
175
        const on_csv_ready = function () {
e86f2462   Antoine Goutenoir   design: refactor ...
176
            for (let i = 0; i <= maxDistance / sliceThickness; i++) {
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
177
178
179
180
181
182
183
184
185
                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);
e86f2462   Antoine Goutenoir   design: refactor ...
186
187
                emissionsPerGroup[Math.floor(distance_km / sliceThickness)] += parseFloat(co2_kg);
                attendeeNumberPerGroup[Math.floor(distance_km / sliceThickness)] += attendeeNumber;
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
188
189
190
191
192
193
194
195
                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...
196

8daea46b   Antoine Goutenoir   fix: interactive ...
197
            // Title
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
198
199
            svg.append("text")
                .attr("transform",
990a9752   Antoine Goutenoir   feat: clean the h...
200
                    "translate(" + (0) + ", " + (-18) + ")")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
201
202
203
                .style("font-weight", "bold")
                .style("font-size", "130%")
                .text("Emissions per distance");
910464a0   Antoine Goutenoir   feat: switch to d...
204

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
            // 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...
221

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
222
223
224
225
226
227
228
229
230
            // 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...
231

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
232
233
234
235
236
237
238
239
240
241
            // 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...
242

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
243
244
245
            svg.append("text")
                .attr("transform",
                    "translate(" + (width / 2) + " ," +
79eadc9f   Antoine Goutenoir   feat: polish
246
                    (height + margin.top + 2) + ")")
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
247
248
                .style("text-anchor", "middle")
                .text("Distance travelled (km)");
910464a0   Antoine Goutenoir   feat: switch to d...
249

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
250
251
252
253
            svg.append("text")
                .attr("transform",
                    "translate(" + (width) + ", 0), rotate(-90)")
                .attr("x", 0 - (height / 2))
79eadc9f   Antoine Goutenoir   feat: polish
254
                .attr("y", 13 + margin.right / 2.0)
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
255
                .style("text-anchor", "middle")
79eadc9f   Antoine Goutenoir   feat: polish
256
                .text("Share of emission (%)");
910464a0   Antoine Goutenoir   feat: switch to d...
257

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
258
259
            svg.append("text")
                .attr("transform", "rotate(-90)")
79eadc9f   Antoine Goutenoir   feat: polish
260
                .attr("y", 0 - (5 * margin.left / 6.0))
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
261
262
263
                .attr("x", 0 - (height / 2))
                .attr("dy", "1em")
                .style("text-anchor", "middle")
79eadc9f   Antoine Goutenoir   feat: polish
264
                .text("Emission (kgCO2e)");
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
265
            // set the parameters for the histogram
8daea46b   Antoine Goutenoir   fix: interactive ...
266
            const histogram = d3.histogram()
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
267
                .domain(x.domain())  // then the domain of the graphic
e86f2462   Antoine Goutenoir   design: refactor ...
268
                .thresholds(x.ticks(Math.floor(maxDistance / sliceThickness))); // then the numbers of bins
910464a0   Antoine Goutenoir   feat: switch to d...
269

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
270
271
272
273
            let histolol = histogram(0);
            // console.log(histolol);
            let barSettings = [];
            emissionsPerGroup.forEach((element, index) => {
990a9752   Antoine Goutenoir   feat: clean the h...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
                barSettings[index] = {
                    height: element,
                    leftBorder: histolol[index].x0,
                    rightBorder: histolol[index].x1,
                };
                if (attendeeNumberPerGroup[index] > 0) {
                    svg.append("text")
                        .attr("transform", "translate(" + ((x(histolol[index].x0) + x(histolol[index].x1)) / 2) + margin.left + ", " + (yl(element) - 15) + ")")
                        .attr("y", 0)
                        .attr("x", 0)
                        .attr("dy", "1em")
                        .style("text-anchor", "middle")
                        .style("font-size", "0.618em")
                        .text(attendeeNumberPerGroup[index] + "👱");
                }
ad528ad0   Antoine Goutenoir   fix: use DOMConte...
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
                // 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...
309
310
        };

ad528ad0   Antoine Goutenoir   fix: use DOMConte...
311
312
313
        d3.csv(csvUrl, on_csv_datum)
            .then(on_csv_ready);
    });
11ab5596   Adrenesis   Add emission-per-...
314

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