Home >  > Js读取csv并用chart.js展示

Js读取csv并用chart.js展示

一、成果展示

二、代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js" integrity="sha512-GMGzUEevhWh8Tc/njS0bDpwgxdCJLQBWG3Z2Ct+JGOpVnEmjvNx6ts4v6A2XJf1HOrtOsfhv3hBKpK9kE5z8AQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
    <!-- <canvas id ="chart" width = "400" height="400"></canvas> -->
    <canvas id="myChart" width="200" height="200"></canvas>
    <script>

const xlabels = [];
const ytemps = [];


chatIt()

    async function chatIt()  {
        await getData(); 
        const ctx = document.getElementById('myChart').getContext('2d');
        const myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: xlabels,
                datasets: [{
                    label: '# Global Average Temprature',
                    data: ytemps,
                    fill:false,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                    ],
                    borderWidth: 1
                }]
            },

        });
    } 

        

    async function getData(){
        const response = await fetch('ZonAnn.Ts+dSST.csv');
        const data = await response.text();
        // console.log(data);
        const table = data.split('\n').slice(1);
        table.forEach(row=>{
            const columns = row.split(',');              
            const year = columns[0];
            xlabels.push(year);
            const temp = columns[1];
            ytemps.push(parseFloat(temp)+14);
            console.log(year,temp);

        })
    }



    </script>
    
</body>
</html>

参考:https://www.youtube.com/watch?v=5-ptp9tRApM&list=PLRqwX-V7Uu6YxDKpFzf_2D84p0cyk4T7X&index=5

暧昧帖

本文暂无标签