【问题标题】:Chartjs time serie in wrong formatChartjs时间序列格式错误
【发布时间】:2021-04-12 19:51:12
【问题描述】:

我正在使用 Chartjs 显示时间序列,但是当我将此数据作为输入传递时,它什么也没显示。

数据

let serie = [{"x": 1594887960*1000, "y": 95.95},{"x": 1596488640*1000,"y": 42.95}]
      

this.chartJS.data.datasets[0].data = serie
this.chartJS.update()

如果我改用这个,它可以工作。

serie = [{"x": '2020-01-01', "y": 95.95},{"x": '2020-01-31',"y": 42.95}]

但我想为性能、轻松排序和更好的标签(DAY MONTH 格式)加上时间戳。

图表 JS 选项

this.chartJS = new Chart(this.$refs.chart, {
    type: 'line',
    data: {
        datasets: [
            {
                data: [],
                fill: false,
                borderColor: 'rgb(75, 192, 192)',
                stepped: false,
            }
        ]
    },
    options: {
        title:      {
            display: true,
            text:    "Chart.js Time Scale"
        },
        scales: {
            xAxes: [{
                type:       "time",
                time:       {
                    tooltipFormat: 'll',
                    time: {
                        unit: 'day'
                    }
                },
                scaleLabel: {
                    display:     true,
                    labelString: 'Date'
                }
            }]
        }
    }
})

编辑:

解决了

import Chart from 'chart.js/auto';
import { format } from 'date-fns'

format(new Date(data[0]*1000), 'yyyy-MM-dd')

【问题讨论】:

    标签: chart.js


    【解决方案1】:

    您的代码与您提供的初始数据配合得很好。我只更正了 xAxes.time 的定义,但即使没有此更改,它也可以工作。

    也许您使用的是 Chart.js v2 的过时版本,或者您没有使用在单个文件中包含 Moment.js(时间轴所需)的 Chart.js 捆绑版本。

    请在下面查看您的可运行代码:

    const chartJS = new Chart('canvas', {
      type: 'line',
      data: {
        datasets: [{
          data: [],
          fill: false,
          borderColor: 'rgb(75, 192, 192)',
          stepped: false,
        }]
      },
      options: {
        title: {
          display: true,
          text: "Chart.js Time Scale"
        },
        scales: {
          xAxes: [{
            type: "time",
            time: {
              unit: 'day',
              tooltipFormat: 'll'
            },
            scaleLabel: {
              display: true,
              labelString: 'Date'
            }
          }]
        }
      }
    });
    
    let serie = [{"x": 1594887960*1000, "y": 95.95},{"x": 1596488640*1000,"y": 42.95}];      
    chartJS.data.datasets[0].data = serie;
    chartJS.update();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
    <canvas id="canvas"></canvas>

    【讨论】:

    • 我确实使用过这个: import Chart from 'chart.js/auto';从'date-fns'格式导入{格式}(新日期(数据[0]*1000),'yyyy-MM-dd')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多