Chart.js无法正确显示变量的日期

pgky5nke  于 2023-04-20  发布在  Chart.js
关注(0)|答案(1)|浏览(194)

我想在图表中显示我的数据(chart.js)
我找到了一个在线生成器工具并复制了代码。
如果我使用“硬编码”的时间值,它的工作(几乎)正确。(有第二个轴,我不想要,但不知道如何删除。)
但是如果我使用变量“globalDate”中的时间数据,一切都会出错,只有一个数据点显示出来。
HTML文档:
头标内:

<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>  
<script>  
    function DrawTheChart(ChartData,ChartOptions,ChartId,ChartType){ 
         eval('var myLine = new Chart(document.getElementById(ChartId).getContext("2d"),{type:"'+ChartType+ 
         '",data:ChartData,options:ChartOptions});document.getElementById(ChartId).getContext("2d").stroke();')  
    }  
</script>

在主体-标记中:

<canvas id="chart-01" width="600" height="400" style="background-color:rgba(255,255,255,1.00);border:1px rgba(227,36,36,1) solid;border-radius:0px;width:600px;height:400px;padding-left:0px;padding-right:0px;padding-top:0px;padding-bottom:2px"></canvas>

请看“图表数据”。

<script>

function MoreChartOptions(){} 

//Daten holen
console.log(globalDate);
console.log(globalValue);

var ChartData = {
    labels : ["2023-03-25 10:00:00","2023-03-25 10:15:00","2023-03-25 10:30:00","2023-03-25 10:45:00","2023-03-25 11:00:00","2023-03-25 11:15:00","2023-03-25 11:30:00",],
    
//var ChartData = {
        //labels : [globalDate],
        datasets : [{
            data : [25,28,3,4,5,6,7,],
            //data : [globalValue],
            backgroundColor :'#168af7',
            borderColor : 'rgba(65,130,76,0.5)',
            pointBackgroundColor:'#fad541',
            pointBorderColor : '#050505',
            label:"datensatz1"
        }],                
    };
ChartOptions= {
responsive:false,
    layout:{padding: 12},
    scales: {
        xAxes:{
            gridLines:{borderDash:[],},
            scaleLabel:{
                display:true,
                labelString:'Timeline',
                fontColor:'#666666',
                fontSize:8,
            },

        },

    yAxes:{
        gridLines:{borderDash:[],},
        scaleLabel:{
            display:true,
            labelString:'temperature',
            fontColor:'#666666',
            fontSize:8,
        },

    },
},plugins:{
datalabels:{display:true,
    align:'end',
    offset:10,
    font:{
        size:10,
        style:' bold',},},
},
legend:{
    labels:{
        usePointStyle:true,

        generateLabels: function(chart){
            return  chart.data.datasets.map( function( dataset, i ){
                return{
                    text:dataset.label,
                    lineCap:dataset.borderCapStyle,
                    lineDash:[],
                    lineDashOffset: 0,
                    lineJoin:dataset.borderJoinStyle,
                    pointStyle:'dash',
                    fillStyle:dataset.backgroundColor,
                    strokeStyle:dataset.backgroundColor,
                    lineWidth:dataset.pointBorderWidth,
                    lineDash:dataset.borderDash,
                }
            })
        },

    },
},

title:{
    display:true,
    text:'Chart Title',
    fontColor:'#3498db',
    fontSize:20,
    fontStyle:' bold',
    },
elements: {
    arc: {
},
    point: {radius:5,},
    line: {tension:0.4,fill:false,
},
    rectangle: {
},
},
tooltips:{
},
hover:{
    mode:'nearest',
    animationDuration:400,
},
};
DrawTheChart(ChartData,ChartOptions,"chart-01","line");
</script>

使用硬定义的“ChartData标签”,图表显示了点,但如果我使用数组,它就不起作用了。
hard defined labels
labels from variable
“globalDate”是这样填写的:

var globalDate = [];
var d = new Date(data[i].LogDate); //from JSON Input
globalDate.push(d.toISOString()); //d.toString());

我想我的数组中的日期格式有问题。
控制台输出(globalDate):

[]
0: "2023-03-24T15:34:12.000Z"
1: "2023-03-24T15:34:42.000Z"
2: "2023-03-24T15:35:12.000Z"
//and so on.

谢谢大家!

bttbmeg0

bttbmeg01#

用我的简短例子让它工作起来了。之后就很容易使用JSON数据作为标签和数据点了...:

<html lang="de">
        <head>
            <meta charset="utf-8">
            <link rel="stylesheet" href="/style.css">         
            <title>main</title>  
         
            <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js" integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
            <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>

        </head>

        <body>
           
            <div class="container">
                <canvas id="myChart" width="400" height="200"></canvas>
            </div>
            
            <script>

                //Funktion um Datenpunkte zu holen
                function getData() {
                    var returnval = []; //array
                    var data = [];                   
    
                    data.push(12);
                    data.push(21);
                    data.push(32);
                    data.push(16);
    
                    for(let i=0; i < data.length; i++) {
                        returnval.push(data[i]);                                        
                    }                    
                    //console.log(returnval);
                    return returnval;
                }

                //Funktion um Labelpunkte(Datum) zu holen
                function getLabels() {
                    var returlabels = []; //array
                    
                    //console.log(moment.locale()) ;
                    var data = [];
                    
                    data.push("2015-04-23T13:03:00Z");
                    data.push("2015-04-24T13:33:00Z");
                    data.push("2015-04-25T14:12:00Z");
                    data.push("2015-04-26T17:08:00Z");
    
                          
                    for(let i=0; i < data.length; i++) {
                        let mydate = moment(data[i]) ;     //.format("LLL") ;
                        mydate.locale('de');
                        returlabels.push( mydate.format("LLL") ) ;      // += "{ t: '" + data[i] + "', y: " + data2[i] + " }," ;                                           
                    }
                    
                    //console.log(returlabels);
                    return returlabels;
                }

                //canvas Element für Chart
                var canvas = document.getElementById('myChart');
                
                //Daten
                var data = {
                    labels: getLabels(), //[moment("2015-04-23").format("LLL"), moment("2015-04-24").format("LLL"), moment("2015-04-25").format("LLL"), moment("2015-04-26").format("LLL")],
                    type: "line",
                    datasets: [
                        {
                            data: getData(), //[ 12,21, 32],
                            fill: false,
                            label: "Demo data",
                            //backgroundColor: "green",
                            borderColor: '#3498db',
                            pointBackgroundColor:'#7CFC00',
                            pointBorderColor : 'black',
                        }
                    ]
                };

                //Options
                ChartOptions = {
                    responsive: true,
                    hover: {
                        mode: "nearest",
                        intersect: false,
                        animationDuration:400,
                    },
                    title: {
                        display:true,
                        text:'Chart Title',
                        fontColor:'#3498db',
                        fontSize:20,
                        fontStyle:' bold',
                    },
                    elements: {
                        arc: {},
                        point: {radius:5,},
                        line: {tension:0.4,fill:false,},
                        rectangle: {},
                    },
                };

                //Chart mit Daten und Optionen erstellen
                var myBarChart = Chart.Line(canvas,{
                    data:data,
                    options:ChartOptions,
                });
            
            </script>
            
        </body>
    </html>

相关问题