我正在使用chart.js库。我正在创建一个图表,并希望在x轴上显示日期,如下所示:http://www.chartjs.org/samples/latest/scales/time/line.html
我为图形提供了与上面示例相同的配置(除了图形数据的日期格式),但我的图形显示时间,即凌晨2点,凌晨2点,..而不是日期,即2018-02-01,2018-02-10,...
对于日期格式,我使用Chart.js推荐的moment.js库
我使用了以下代码:
<!doctype html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
</head>
<body>
<div style="width:75%;">
    <canvas id="canvas"></canvas>
</div>
<script>
    var timeFormat = 'YYYY-MM-DD';
    var config = {
        type: 'line',
        data: {
            datasets: [{
                label: "Thi is graph label",
                backgroundColor: "rgb(54, 162, 235)",
                borderColor: "rgb(255, 159, 64)",
                fill: false,
                data: [{
                    x: moment("2010-03-01").format(timeFormat),
                    y: 0.668525
                }, {
                    x: moment("2010-03-02").format(timeFormat),
                    y: 0.668827
                }],
            }]
        },
        options: {
            title: {
                text: "This is title"
            },
            scales: {
                xAxes: [{
                    type: "time",
                    time: {
                        parser: timeFormat,
                        tooltipFormat: 'll HH:mm'
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Date'
                    }
                },],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'value'
                    }
                }]
            },
        }
    };
    window.onload = function () {
        var ctx = document.getElementById("canvas").getContext("2d");
        console.log(config);
        window.myLine = new Chart(ctx, config);
    };
</script>
</body>
</html>
发布于 2019-11-06 23:34:31
您需要设置:
scales: {
   xAxes: [
     {
     .....
        ticks: {
          source: 'date'
        },
     }
     ......
],https://stackoverflow.com/questions/48965407
复制相似问题