Skip to content
Snippets Groups Projects
main.js 52.4 KiB
Newer Older
  • Learn to ignore specific revisions
  •                       tooltip.transition().duration(500).style("opacity", 0); // Transition de disparition du tooltip
                      })
                      .on("click", (event, d) => {
                          const memberColor = colorMap[member]; // Récupérer la couleur du membre
                          showDetailChart(d.month, member, selectedYear, memberColor); // Passer la couleur à la fonction showDetailChart
                      });
              });
              
          }
          
         // Fonction pour afficher les détails
         function showDetailChart(month, member, year, memberColor) {
          // Affiche le modal
          const modal = d3.select("#modal");
          modal.style("display", "block");
      
          // Fermer le modal
          modal.select(".close").on("click", () => {
              modal.style("display", "none");
              d3.select("#detail-visualization").selectAll("*").remove();
          });
      
          const detailContainer = d3.select("#detail-visualization");
          detailContainer.selectAll("*").remove();
      
          const filteredData = data.filter(d => formatYear(d.date) === year.toString() && formatMonth(d.date) === month);
      
          const dailyData = d3.groups(filteredData, d => formatDay(d.date)).map(([day, records]) => ({
              day: day,
              value: d3.mean(records, d => d[`Sleep_${member}`] || 0)
          }));
      
          const detailSvg = detailContainer.append("svg")
              .attr("width", 600)
              .attr("height", 400)
              .append("g")
              .attr("transform", "translate(50, 50)");
      
          const xScale = d3.scaleBand()
              .domain(dailyData.map(d => d.day))
              .range([0, 500])
              .padding(0.1);
      
          const yScale = d3.scaleLinear()
              .domain([0, d3.max(dailyData, d => d.value)]).nice()
              .range([300, 0]);
      
          // Ajout de l'axe X
          detailSvg.append("g")
              .attr("transform", "translate(0, 300)")
              .call(d3.axisBottom(xScale));
      
          // Ajout de l'axe Y
          detailSvg.append("g")
              .call(d3.axisLeft(yScale));
      
          // Titre du graphique
          detailSvg.append("text")
              .attr("x", 250)
              .attr("y", -20)
              .attr("text-anchor", "middle")
              .style("font-size", "16px")
              .text(`${member} - Sommeil du mois de ${month} (${year})`);
      
          // Ajouter la légende de l'axe X (Jours)
          detailSvg.append("text")
              .attr("x", 250)
              .attr("y", 340)
              .attr("text-anchor", "middle")
              .style("font-size", "12px")
              .text("Jours du mois");
      
          // Ajouter la légende de l'axe Y (Heures de sommeil)
          detailSvg.append("text")
              .attr("transform", "rotate(-90)")
              .attr("x", -200)
              .attr("y", -40)
              .attr("text-anchor", "middle")
              .style("font-size", "12px")
              .text("Heures de sommeil moyen");
              
    
          // Dessin des barres
          detailSvg.selectAll(".bar")
              .data(dailyData)
              .enter()
              .append("rect")
              .attr("x", d => xScale(d.day))
              .attr("y", d => {
                  const value = d.value;
                  return value < 0 || value === null ? yScale(2) : yScale(value);
              })
              .attr("width", xScale.bandwidth())
              .attr("height", d => {
                  const value = d.value;
                  return value < 0 || value === null ? 300 - yScale(2) : 300 - yScale(value);
              })
              .attr("fill", d => {
                  const value = d.value;
                  return value < 0 || value === null ? "lightgrey" : memberColor;
              })
              .on("mouseover", function(event, d) {
                tooltip.transition().duration(200).style("opacity", 1);
                tooltip.html(`
                    <div style="text-align: center;">
                      <strong>Jour :</strong> ${d.day}<br>
                      <strong>Sommeil :</strong> ${d.value === -1.0 || d.value === null ? "Pas de données" : d.value.toFixed(2)} heures
                    </div>
                `);
            })
            .on("mousemove", function(event) {
                tooltip
                    .style("left", (event.pageX + 15) + "px") // Décalage pour positionner le tooltip
                    .style("top", (event.pageY + 15) + "px");
            })
            .on("mouseout", function() {
                tooltip.transition().duration(500).style("opacity", 0);
            });
            
      }
      
    
          // Initialisation de la visualisation
          updateVisualization(years[3]);
    
          // Mettre à jour la visualisation lorsque le slider est déplacé
          rangeSlider.on("input", function() {
              const selectedYear = years[this.value];
              yearDisplay.text(selectedYear);
              updateVisualization(selectedYear);
          });
    
    1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    
    
    
    // Visu 5
    function renderSleepActivityVisualization() {
      fetch('../static/js/final_combined_with_all_data.json') // Adapter le chemin si nécessaire
        .then(response => response.json())
        .then(data => {
          const svg = d3.select("#sleep-activity-visualization")
            .append("svg")
            .attr("width", 700)
            .attr("height", 300);
    
          const margin = { top: 20, right: 150, bottom: 50, left: 50 };
          const width = +svg.attr("width") - margin.left - margin.right;
          const height = +svg.attr("height") - margin.top - margin.bottom;
    
          const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
    
          const tooltip = d3.select("body").append("div")
            .attr("class", "tooltip")
            .style("position", "absolute")
            .style("visibility", "hidden")
            .style("background", "#fff")
            .style("border", "1px solid #ccc")
            .style("padding", "5px")
            .style("border-radius", "4px")
            .style("font-size", "12px");
    
          const colorMap = {
            "Maya": "#0f7e06",
            "Corentin": "#1d38e3",
            "Anis": "#d6bff4",
            "Amira": "#7e09bd"
          };
    
          const getISOWeekNumber = (date) => {
            const tempDate = new Date(date);
            tempDate.setHours(0, 0, 0, 0);
            tempDate.setDate(tempDate.getDate() + 4 - (tempDate.getDay() || 7));
            const yearStart = new Date(tempDate.getFullYear(), 0, 1);
            return Math.ceil(((tempDate - yearStart) / 86400000 + 1) / 7);
          };
    
          const filteredData = data.filter(d => {
            const date = new Date(d.date);
            return date >= new Date("2023-10-01") && date <= new Date("2024-12-31");
          });
    
          const groupedData = d3.group(filteredData, d => {
            const date = new Date(d.date);
            const weekNumber = getISOWeekNumber(date);
            return `${date.getFullYear()}-W${weekNumber}`;
          });
    
          const processedData = Array.from(groupedData, ([week, records]) => {
            return records.map(d => ([
              { name: "Anis", steps: d.Steps_Anis, sleep: d.Sleep_Anis, calories: d.Calories_Anis },
              { name: "Maya", steps: d.Steps_Maya, sleep: d.Sleep_Maya, calories: d.Calories_Maya },
              { name: "Corentin", steps: d.Steps_Corentin, sleep: d.Sleep_Corentin, calories: d.Calories_Corentin },
              { name: "Amira", steps: d.Steps_Amira, sleep: d.Sleep_Amira, calories: d.Calories_Amira }
            ].filter(d => d.steps > 0 && d.sleep > 0))).flat();
          });
    
          const x = d3.scaleLinear()
            .domain([0, Math.ceil(d3.max(processedData.flat(), d => d.steps))])
            .range([0, width]);
    
          const y = d3.scaleLinear()
            .domain([0, 18])
            .range([height, 0]);
    
          const radius = d3.scaleSqrt()
            .domain([0, Math.ceil(d3.max(processedData.flat(), d => d.calories))])
            .range([3, 15]);
    
          g.append("g")
            .attr("transform", `translate(0,${height})`)
            .call(d3.axisBottom(x).ticks(10))
            .append("text")
            .attr("fill", "black")
            .attr("x", width / 2)
            .attr("y", 40)
            .attr("text-anchor", "middle")
            .text("Steps");
    
          g.append("g")
            .call(d3.axisLeft(y))
            .append("text")
            .attr("fill", "black")
            .attr("transform", "rotate(-90)")
            .attr("x", -height / 2)
            .attr("y", -40)
            .attr("text-anchor", "middle")
            .text("Sleep (hours)");
    
          const legend = svg.append("g")
            .attr("transform", `translate(${width + 20}, 50)`);
    
          legend.selectAll("rect")
            .data(Object.keys(colorMap))
            .enter()
            .append("rect")
            .attr("x", 0)
            .attr("y", (d, i) => i * 20)
            .attr("width", 15)
            .attr("height", 15)
            .attr("fill", d => colorMap[d]);
    
          legend.selectAll("text")
            .data(Object.keys(colorMap))
            .enter()
            .append("text")
            .attr("x", 20)
            .attr("y", (d, i) => i * 20 + 12)
            .text(d => d);
    
          const slider = document.getElementById("date-slider");
          const playButton = document.getElementById("play-button");
          let playing = false;
          let interval;
    
          slider.max = processedData.length - 1;
    
          const update = (index) => {
            const currentData = processedData[index];
            const weekLabel = Array.from(groupedData.keys())[index];
    
            document.getElementById("date-label").textContent = weekLabel;
    
            g.selectAll("circle").remove();
    
            g.selectAll("circle")
              .data(currentData)
              .enter()
              .append("circle")
              .attr("cx", d => x(d.steps))
              .attr("cy", d => y(d.sleep))
              .attr("r", d => radius(d.calories))
              .attr("fill", d => colorMap[d.name])
              .attr("opacity", 0.7)
              .on("mouseover", (event, d) => {
                tooltip.style("visibility", "visible")
                  .text(`${d.name}: Steps: ${d.steps}, Sleep: ${d.sleep}, Calories: ${d.calories}`);
              })
              .on("mousemove", event => {
                tooltip.style("top", `${event.pageY - 10}px`)
                  .style("left", `${event.pageX + 10}px`);
              })
              .on("mouseout", () => {
                tooltip.style("visibility", "hidden");
              });
          };
    
          playButton.addEventListener("click", () => {
            if (!playing) {
              playing = true;
              playButton.textContent = "Pause";
              let index = 0;
              interval = setInterval(() => {
                if (index >= processedData.length) {
                  clearInterval(interval);
                  playButton.textContent = "Play";
                  playing = false;
                } else {
                  slider.value = index;
                  update(index);
                  index++;
                }
              }, 1000);
            } else {
              clearInterval(interval);
              playButton.textContent = "Play";
              playing = false;
            }
          });
    
          slider.addEventListener("input", (event) => update(+event.target.value));
    
          update(0);
        })
        .catch(error => console.error("Error loading data:", error));
    }
    // Visu 6
    function renderRadialDistanceChart() {
      fetch("../static/js/final_combined_with_all_data.json")
        .then((response) => response.json())
        .then((data) => {
          const width = 600;
          const height = 600;
          const innerRadius = 50;
          const outerRadius = Math.min(width, height) / 2 - 100;
    
          // Filter data
          const filteredData = data.filter((d) => {
            const date = new Date(d.date);
            return date >= new Date("2023-10-01") && date <= new Date("2024-12-31");
          });
    
          // Group data by ISO week
          const groupedData = d3.group(filteredData, (d) => {
            const date = new Date(d.date);
            const weekNumber = getISOWeekNumber(date);
            return `${date.getFullYear()}-W${weekNumber}`;
          });
    
          const processedData = Array.from(groupedData, ([week, records]) => {
            const aggregated = {
              week: week,
              year: week.split("-")[0], // Extract the year from the week
              Distance_Anis: d3.sum(records, (d) => (d.Distance_Anis > 0 ? d.Distance_Anis : 0)),
              Distance_Maya: d3.sum(records, (d) => (d.Distance_Maya > 0 ? d.Distance_Maya : 0)),
              Distance_Corentin: d3.sum(records, (d) => (d.Distance_Corentin > 0 ? d.Distance_Corentin : 0)),
              Distance_Amira: d3.sum(records, (d) => (d.Distance_Amira > 0 ? d.Distance_Amira : 0)),
              Sleep_Anis: d3.mean(records, (d) => (d.Sleep_Anis > 0 ? d.Sleep_Anis : 0)),
              Sleep_Maya: d3.mean(records, (d) => (d.Sleep_Maya > 0 ? d.Sleep_Maya : 0)),
              Sleep_Corentin: d3.mean(records, (d) => (d.Sleep_Corentin > 0 ? d.Sleep_Corentin : 0)),
              Sleep_Amira: d3.mean(records, (d) => (d.Sleep_Amira > 0 ? d.Sleep_Amira : 0)),
            };
            return aggregated;
          });
    
          const dropdown = document.getElementById("personDropdown");
          dropdown.addEventListener("change", () => updateChart(dropdown.value));
    
          // Initial chart rendering
          updateChart(dropdown.value);
    
          function updateChart(personKey) {
            const sleepKey = personKey.replace("Distance", "Sleep");
            d3.select("#chart").html(""); // Clear the previous chart
    
            const svg = d3.select("#chart")
              .append("svg")
              .attr("width", width)
              .attr("height", height)
              .attr("viewBox", [-width / 2, -height / 2, width, height])
              .attr("style", "width: 100%; height: auto; font: 10px sans-serif;");
    
            // Scales
            const x = d3.scaleBand()
              .domain(processedData.map((d) => d.week))
              .range([0, 2 * Math.PI])
              .align(0);
    
            const y = d3.scaleRadial()
              .domain([0, d3.max(processedData, (d) => d[personKey])])
              .range([innerRadius, outerRadius]);
    
            const color = d3.scaleLinear()
              .domain([0, d3.max(processedData, (d) => d[sleepKey])])
              .range(["lightblue", "darkblue"]);
    
            // Add year to the center
            const uniqueYears = [...new Set(processedData.map((d) => d.year))];
            if (uniqueYears.length === 1) {
              svg
                .append("text")
                .attr("text-anchor", "middle")
                .attr("dy", "0.35em")
                .style("font-size", "20px")
                .text(uniqueYears[0]);
            }
    
            // Bars
    svg.append("g")
    .selectAll("path")
    .data(processedData)
    .join("path")
    .attr("d", d3.arc()
      .innerRadius(innerRadius)
      .outerRadius((d) => d[personKey] > 0 ? y(d[personKey]) : y(20)) // Hauteur fixe (20 km) pour valeurs manquantes
      .startAngle((d) => x(d.week))
      .endAngle((d) => x(d.week) + x.bandwidth())
      .padAngle(0.02)
      .padRadius(innerRadius))
    .attr("fill", (d) => d[personKey] > 0 ? color(d[sleepKey]) : "#ccc") // Couleur grise pour valeurs manquantes
    .append("title")
    .text((d) => `${d.week}\nDistance: ${d[personKey] > 0 ? d[personKey].toFixed(2) : "N/A"}\nSleep: ${d[sleepKey] > 0 ? d[sleepKey].toFixed(2) + "h" : "N/A"}`);
    
            // Week Labels with grouped years
    svg.append("g")
    .selectAll("g")
    .data(processedData)
    .join("g")
    .attr("transform", (d) => {
      const midAngle = (x(d.week) + x.bandwidth() / 2) * 180 / Math.PI - 90;
      const radius = outerRadius + 25;
      return `
        rotate(${midAngle})
        translate(${radius},0)
      `;
    })
    .call((g) => {
      g.append("text")
        .text((d, i) => {
          // Only show the year once for the first week of each year
          if (i === 0 || d.year !== processedData[i - 1].year) {
            return `${d.year} ${d.week.split("-")[1]}`;
          }
          return `${d.week.split("-")[1]}`;
        })
        .attr("text-anchor", "middle");
    });
    // Legend
    const defs = svg.append("defs");
    const gradient = defs.append("linearGradient")
      .attr("id", "sleepGradient")
      .attr("x1", "0%")
      .attr("y1", "0%")
      .attr("x2", "100%")
      .attr("y2", "0%");
    
    gradient.append("stop").attr("offset", "0%").attr("stop-color", "lightblue");
    gradient.append("stop").attr("offset", "100%").attr("stop-color", "darkblue");
    
    const legend = svg.append("g")
      .attr("transform", `translate(${-width / 2 + 30}, ${-height / 2 + 50})`); // Position à gauche
    
    // Title
    legend.append("text")
      .attr("y", 0)
      .attr("x", 0)
      .text("Durée de sommeil")
      .attr("font-size", "12px")
      .attr("text-anchor", "start")
      .attr("font-weight", "bold");
    
    // Gradient bar
    legend.append("rect")
      .attr("x", 0)
      .attr("y", 15) // Space below the title
      .attr("width", 100) // Longer gradient for better visibility
      .attr("height", 10)
      .style("fill", "url(#sleepGradient)");
    
    // Min and Max values for sleep
    legend.append("text")
      .attr("x", -5) // Align with start of gradient
      .attr("y", 35)
      .text(`${d3.min(processedData, (d) => d[sleepKey]).toFixed(1)}h`)
      .attr("font-size", "10px")
      .attr("text-anchor", "start");
    
    legend.append("text")
      .attr("x", 105) // Align with end of gradient
      .attr("y", 35)
      .text(`${d3.max(processedData, (d) => d[sleepKey]).toFixed(1)}h`)
      .attr("font-size", "10px")
      .attr("text-anchor", "start");
    
    // Gray bar for missing data
    legend.append("rect")
      .attr("x", 0)
      .attr("y", 50) // Space below the gradient
      .attr("width", 100) // Same width as gradient for consistency
      .attr("height", 10)
      .style("fill", "#ccc");
    
    // Label for gray bar
    legend.append("text")
      .attr("x", 0) // Align with start of gray bar
      .attr("y", 70) // Space below the gray bar
      .text("Valeur manquante")
      .attr("font-size", "10px")
      .attr("text-anchor", "start");
    
    
            // Add radial distance circles
    const distanceTicks = y.ticks(5); // Nombre de cercles (5 niveaux ici)
    const circleGroup = svg.append("g")
      .attr("class", "distance-circles");
    
    // Dessiner les cercles
    circleGroup.selectAll("circle")
      .data(distanceTicks)
      .join("circle")
      .attr("r", (d) => y(d))
      .attr("fill", "none")
      .attr("stroke", "#ccc")
      .attr("stroke-dasharray", "4 2"); // Ligne pointillée (facultatif)
    
    // Ajouter les étiquettes pour les distances
    circleGroup.selectAll("text")
      .data(distanceTicks)
      .join("text")
      .attr("x", 0)
      .attr("y", (d) => -y(d)) // Positionné au-dessus des cercles
      .attr("dy", "-0.3em")
      .attr("text-anchor", "middle")
      .attr("font-size", "10px")
      .text((d) => `${d.toFixed(0)} km`); // Format pour afficher les valeurs
          }
        })
        .catch((error) => console.error("Error loading data:", error));
    
        function getISOWeekNumber(date) {
          const tempDate = new Date(date);
          tempDate.setDate(tempDate.getDate() + 4 - (tempDate.getDay() || 7));
          const yearStart = new Date(tempDate.getFullYear(), 0, 1);
          return Math.ceil(((tempDate - yearStart) / 86400000 + 1) / 7);
        }
    
    }
    
    
    
    document.addEventListener("DOMContentLoaded", function () {
      renderStepsVisualization();
      renderDistanceVisualization();
      renderCaloriesVisualization();
    
      renderSleepVisualization();
    
      renderSleepActivityVisualization();
      renderRadialDistanceChart()