🗺️TD 3 (séance 3)

Lundi 23/10, 14h00 ou mardi 24/10, 8h00

Tips

Paramètres l'axe Y

const myChart = new Chart(
  document.getElementById('myChart'),
  {
    type: 'line',
    data: {
      labels: ['1', '2', '3', '4', '5'],
      datasets: [{
        label: 'A',
        data: [100, 96, 84, 76, 69],
        fill: true,
      }]
    },
    options: {
      scales: {
        y: {
          min: 0,
          max: 100
        }
      }
    }
  }
);

Deux axes

const myChart = new Chart(
  document.getElementById('myChart'),
  {
    type: 'line',
    data: {
      labels: ['1', '2', '3', '4', '5'],
      datasets: [{
        label: 'A',
        yAxisID: 'A',
        data: [100, 96, 84, 76, 69],
        fill: true,
      }, {
        label: 'B',
        yAxisID: 'B',
        backgroundColor: 'rgb(122, 99, 255)',
        borderColor: 'rgba(102, 99, 255, 0.2)',
        data: [1, 1, 0.5, 1, 0],
        fill: false,
      }]
    },
    options: {
      scales: {
        A: {
          type: 'linear',
          position: 'left',
        },
        B: {
          type: 'linear',
          position: 'right',
          ticks: {
            max: 1,
            min: 0
          }
        }
      }
    }
  }
);

Choix des données

Le HTML

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js" defer></script>
    <script src="assets/js/demo3.js" defer></script>
</head>
<body>
    <canvas id="graph"></canvas>
    <div>
        <input type="checkbox" id="check1" value="A" data-color="rgb(120,123,21)" data-label="A" data-value="[1, 3, 4, 6]">A
        <input type="checkbox" id="check1" value="B" data-color="rgb(21,123,121)" data-label="B" data-value="[4, 2, 41, 12]">B
        <input type="checkbox" id="check1" value="C" data-color="rgb(20,13,21)" data-label="C" data-value="[2, 0, 9, 6]">C
        <input type="checkbox" id="check1" value="D" data-color="rgb(120,13,21)" data-label="D" data-value="[10, 3, 7, 1]">D
    </div>
</body>
</html>

Le JS

const myChart = new Chart(
    document.getElementById('graph'),
    {
        type: 'line',
        data: {
            labels: ['1', '2', '3', '4'],
            datasets: []
        },
    }
);

document.querySelectorAll('input[type=checkbox]').forEach((e) => {
    e.addEventListener('click', (el) => {
        console.log('check')
        if (el.target.checked) {
            val = el.currentTarget.dataset.value.substring(1, el.currentTarget.dataset.value.length - 1).split(', ');
            obj = {
                label: el.currentTarget.dataset.label,
                data: val,
                fill: false,
                backgroundColor: el.currentTarget.dataset.color,
                borderColor: el.currentTarget.dataset.color,
            }
            myChart.data.datasets.push(obj);
            myChart.update()
        } else {
            myChart.data.datasets = myChart.data.datasets.filter((e) => e.label !== el.currentTarget.dataset.label)
            myChart.update()
        }
    })
})

Afficher une carte

Avec d3js : Installer D3js : https://www.datavis.fr/d3js/firststep

Le fichier html/JS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        .map-tooltip {
            position: absolute;
            text-align: center;
            z-index: 1000;
            color: black;
            width: 275px;
            height: 37px;
            padding: 2px;
            font: 12px sans-serif;
            background: grey;
            border: 0px;
            border-radius: 8px;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div id="map"></div>

    <script>
        const width = 550, height = 550;
        const path = d3.geoPath();
        const projection = d3.geoConicConformal()
            .center([2.454071, 46.279229])
            .scale(2600)
            .translate([width / 2, height / 2]);
        path.projection(projection);

        const svg = d3.select('#map').append("svg")
            .attr("id", "svg")
            .attr("width", width)
            .attr("height", height);

        const deps = svg.append("g");

        d3.json('assets/js/departments.json').then(function (geojson) {
            deps.selectAll("path")
                .data(geojson.features)
                .enter()
                .append("path")
                .attr('class', 'department')
                .attr("d", path)//récupère chaque path (chaque département), possible de changer la couleur de path avec un attribut sur le SVG
                .on("mouseover", function (event, d) {
                    console.log(d)//d contient les informations du département survolé
                    div.transition()
                        .duration(200)
                        .style("opacity", .9);
                    div.html("Département : " + d.properties.NOM_DEPT + "<br/>"
                        + "Région : " + d.properties.NOM_REGION)
                        .style("left", (event.pageX + 30) + "px")
                        .style("top", (event.pageY - 30) + "px")
                })
                .on("mouseout", function (event, d) {
                    div.style("opacity", 0);
                    div.html("")
                        .style("left", "-500px")
                        .style("top", "-500px");
                });
        });

        let div = d3.select("body").append("div")
            .attr("class", "map-tooltip")
            .style("opacity", 0);
    </script>
</body>

</html>

Il faut récupérer un fichier geoJson ici : https://github.com/gregoiredavid/france-geojson

Et le charger à la place de departements.json

Un autre exemple de carte avec des couleurs : https://www.datavis.fr/d3js/map-population

  • Il faut ici une source CSV pour avoir les données de population.

Ou encore un autre exemple ici : https://www.datavis.fr/d3js/map-improve

Dernière mise à jour