如何使我的Type:Time可以与折线图一起使用?

时间:2019-06-24 17:01:34

标签: chart.js

我正在创建一个折线图,以绘制一天中不同时间在不同天的点,为此,我需要使用类型:xAxes上的时间。我已经下载了moment.js,但是type:time给我一个错误。如果没有type:time,则X轴标签太长,使图形看起来很糟。有什么想法需要解决吗?

我试图以这种方式放置数据点: 数据:[{x:newDate(2019,06,24,08,00),y:24}] 但是它仍然不能与类型:time

一起使用
<canvas id="timechart" width="800" height="400"  role="img"></canvas>
<script>
    var ctx = document.getElementById('timechart');
    var timeFormat = 'MM/DD/YY HH:mm';
    function newDate(days) {
        return moment().add(days).toDate();
    }
    function newDateString(days) {
        return moment().add(days).format();
    }
    var timechart = new Chart(ctx, {
        type: "line",
        data: {
            labels: [newDate(0), newDate(1), newDate(2), newDate(3), 
newDate(4), newDate(5), newDate(6), newDate(7), newDate(8), newDate(9), 
newDate(10), newDate(11),
            newDate(12), newDate(13), newDate(14), newDate(15), 
newDate(16), newDate(17)],
            datasets: [
                {
                    data: [12, 21, 32, 25, 16, 14, 7, 25, 18, 20, 22, 15, 
17, 11, 19, 28, 30, 10],
                    label: 'D Speed',
                    fill: false,
                    backgroundColor: 'rgba(102, 147, 188, 1)',
                    borderColor: 'rgba(102, 147, 188, 1)',
                    radius: 4,
                    hoverRadius: 5,
                }, {
                    data: [8, 16, 24, 30, 20, 10, 12, 21, 32, 15, 17, 11, 
22, 18, 29, 17, 8],
                    label: 'U Speed',
                    fill: false,
                    backgroundColor: 'rgba(255, 147, 44, 1)',
                    borderColor: 'rgba(255, 147, 44, 1)',
                    radius: 4,
                    hoverRadius: 5,
                }
            ],
        },
        options: {
            title: {
                display: true,
            },
            scales: {
                xAxes: [{
                    display: true,
                    type: 'time',
                }],
                yAxis: [{
                    display: true,
                }]
            },

        }
    });

</script>

我希望x轴标签仅显示MM / DD / YY HH:MM,但实际上根本不显示图表。

1 个答案:

答案 0 :(得分:0)

您共享的代码对我有用。确保在项目中包括Moment和Chart.js的非捆绑版本。例如:

<script src="https://cdn.jsdelivr.net/npm/moment@2.24.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

此外,请检查您浏览器的开发人员控制台,以查看是否存在任何JavaScript错误,可以为问题提供更多线索。您可以通过按F12键在Chrome中访问。