Skip to content
Snippets Groups Projects
script.js 8.45 KiB
Newer Older
  • Learn to ignore specific revisions
  • BOUDJEBBOUR MAYA p2312048's avatar
    BOUDJEBBOUR MAYA p2312048 committed
    // Charger les données depuis le fichier JSON
    fetch('final_combined_with_all_data.json')
        .then((response) => response.json())
        .then((data) => {
            const parseDate = d3.timeParse("%Y-%m-%d");
            const formatMonth = d3.timeFormat("%Y-%m");
            const formatYear = d3.timeFormat("%Y");
    
            const members = ["Corentin", "Maya", "Anis", "Amira"];
            data.forEach(d => d.date = parseDate(d.date));
    
            // Extraire les années uniques
            const years = Array.from(new Set(data.map(d => formatYear(d.date))));
    
            // Ajouter les années dans le sélecteur d'année
            const yearSelect = d3.select("#yearSelect");
            yearSelect.selectAll("option")
                .data(years)
                .enter()
                .append("option")
                .attr("value", d => d)
                .text(d => d);
    
            // Regrouper les données par mois
            function groupDataByMonth(yearFilter = null) {
                let filteredData = yearFilter ? data.filter(d => formatYear(d.date) === yearFilter) : data;
                return d3.groups(filteredData, d => formatMonth(d.date));
            }
    
            // Fonction pour transformer les données en données agrégées
            function getAggregatedData(groupedData) {
                return groupedData.map(([timePeriod, records]) => {
                    const aggregated = { timePeriod };
                    members.forEach(member => {
                        aggregated[`Steps_${member}`] = d3.mean(records, d => d[`Steps_${member}`] > 0 ? d[`Steps_${member}`] : 0);
                        aggregated[`Sleep_${member}`] = d3.mean(records, d => d[`Sleep_${member}`] > 0 ? d[`Sleep_${member}`] : 0);
                    });
                    return aggregated;
                });
            }
    
            // Étape 2 : Dimensions et marges
    
    BOUDJEBBOUR MAYA p2312048's avatar
    BOUDJEBBOUR MAYA p2312048 committed
            const margin = { top: 50, right: 250, bottom: 50, left: 70 }; // Augmenter la marge droite pour la légende
    
    BOUDJEBBOUR MAYA p2312048's avatar
    BOUDJEBBOUR MAYA p2312048 committed
            const width = 1000 - margin.left - margin.right;
            const height = 500 - margin.top - margin.bottom;
    
            // Étape 3 : Créer le conteneur SVG
            const svg = d3.select("#visualization")
                .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", `translate(${margin.left},${margin.top})`);
    
            // Étape 4 : Mise à jour de la visualisation
            function updateVisualization(yearSelected) {
                let groupedData = groupDataByMonth(yearSelected);
                const dataToDisplay = getAggregatedData(groupedData);
    
                // Étape 5 : Créer les échelles pour l'affichage
                const xScale = d3.scaleBand()
                    .domain(dataToDisplay.map(d => d.timePeriod))
                    .range([0, width])
                    .padding(0.2);
    
                const yScaleSteps = d3.scaleLinear()
                    .domain([0, d3.max(dataToDisplay, d => {
                        return Math.max(...members.map(member => d[`Steps_${member}`]));
                    })])
                    .range([height, 0]);
    
                const yScaleSleep = d3.scaleLinear()
                    .domain([0, d3.max(dataToDisplay, d => {
                        return Math.max(...members.map(member => d[`Sleep_${member}`]));
                    })])
                    .range([height, 0]);
    
                const colorScale = d3.scaleOrdinal(d3.schemeCategory10).domain(members);
    
                // Effacer l'ancien contenu SVG avant de redessiner
                svg.selectAll("*").remove();
    
                // Étape 6 : Ajouter les axes
                svg.append("g")
                    .attr("class", "x-axis")
                    .attr("transform", `translate(0, ${height})`)
                    .call(d3.axisBottom(xScale));
    
                svg.append("g")
                    .attr("class", "y-axis-steps")
                    .call(d3.axisLeft(yScaleSteps))
                    .append("text")
                    .attr("fill", "black")
                    .attr("x", -50)
                    .attr("y", -10)
                    .attr("text-anchor", "middle")
                    .attr("transform", "rotate(-90)")
                    .text("Nombre de pas");
    
                svg.append("g")
                    .attr("class", "y-axis-sleep")
                    .attr("transform", `translate(${width}, 0)`)
                    .call(d3.axisRight(yScaleSleep))
                    .append("text")
                    .attr("fill", "black")
                    .attr("x", 50)
                    .attr("y", -10)
                    .attr("text-anchor", "middle")
                    .attr("transform", "rotate(-90)")
                    .text("Durée de sommeil (heures)");
    
                // Étape 7 : Ajouter les barres pour les pas
                members.forEach((member, i) => {
                    svg.selectAll(`.bar-steps-${member}`)
                        .data(dataToDisplay)
                        .enter()
                        .append("rect")
                        .attr("class", `bar-steps-${member}`)
                        .attr("x", d => xScale(d.timePeriod) + i * (xScale.bandwidth() / members.length))
                        .attr("y", d => yScaleSteps(d[`Steps_${member}`]))
                        .attr("width", xScale.bandwidth() / members.length)
                        .attr("height", d => height - yScaleSteps(d[`Steps_${member}`]))
                        .attr("fill", colorScale(member))
                        .attr("opacity", 0.7);
                });
    
                // Étape 8 : Ajouter les lignes pour le sommeil
                const line = d3.line()
                    .x(d => xScale(d.timePeriod) + xScale.bandwidth() / 2)
                    .y(d => yScaleSleep(d.value));
    
                members.forEach(member => {
                    const sleepData = dataToDisplay.map(d => ({ timePeriod: d.timePeriod, value: d[`Sleep_${member}`] }));
    
                    svg.append("path")
                        .datum(sleepData)
                        .attr("fill", "none")
                        .attr("stroke", colorScale(member))
                        .attr("stroke-width", 2)
                        .attr("d", line);
                });
    
    BOUDJEBBOUR MAYA p2312048's avatar
    BOUDJEBBOUR MAYA p2312048 committed
    
                // Étape 9 : Ajouter une légende explicative à côté du graphique
                const legendContainer = svg.append("g")
                    .attr("transform", `translate(${width + 30}, 0)`); // Décalage de la légende
    
                // Légende pour les heures de sommeil
                legendContainer.append("line")
                    .attr("x1", 0)
                    .attr("y1", 0)
                    .attr("x2", 100)
                    .attr("y2", 0)
                    .attr("stroke", "blue")
                    .attr("stroke-width", 2);
    
                legendContainer.append("text")
                    .attr("x", 110)
                    .attr("y", 0)
                    .text("Nb heures de sommeil")
                    .style("font-size", "12px")
                    .attr("alignment-baseline", "middle");
    
                // Légende pour le nombre de pas
                legendContainer.append("rect")
                    .attr("x", 0)
                    .attr("y", 20)
                    .attr("width", 45)
                    .attr("height", 10)
                    .attr("fill", "blue");
    
                legendContainer.append("text")
                    .attr("x", 110)
                    .attr("y", 25)
                    .text("Nb pas")
                    .style("font-size", "12px")
                    .attr("alignment-baseline", "middle");
    
                // Légende pour les couleurs des membres
                members.forEach((member, i) => {
                    legendContainer.append("rect")
                        .attr("x", 0)
                        .attr("y", 40 + i * 20)
                        .attr("width", 15)
                        .attr("height", 15)
                        .attr("fill", colorScale(member));
    
                    legendContainer.append("text")
                        .attr("x", 20)
                        .attr("y", 50 + i * 20)
                        .text(member)
                        .style("font-size", "12px")
                        .attr("alignment-baseline", "middle");
                });
    
    BOUDJEBBOUR MAYA p2312048's avatar
    BOUDJEBBOUR MAYA p2312048 committed
            }
    
            // Initialisation de la visualisation avec l'année par défaut (par exemple, la première année)
            updateVisualization(years[0]);
    
            // Écouter les changements dans le sélecteur d'année
            d3.select("#yearSelect").on("change", function(event) {
                const yearSelected = event.target.value;
                updateVisualization(yearSelected);
            });
    
        })
        .catch((error) => console.error("Erreur lors du chargement des données :", error));