首页 > 解决方案 > Chart.js x 轴,日期为 DD-MM-YYYY - React

问题描述

我正在尝试使用库显示图表Chart.js

我的数据格式为:

data: [["15-11-2019", 25], ["16-11-2019", 35], ["17-11-2019", 40], ["18-11-2019", 20], ["19-11-2019", 15]]

我无法在时间轴上转换 x 轴。

我试图将类型传递给options参数,time但它似乎不起作用。图形渲染,但 x 轴不存在,只有 y 轴存在。

import React, {Component,  useState, useEffect, useCallback} from 'react';
import Plot from 'react-plotly.js';
import { Chart } from 'react-charts'

function MyChart() {
    const data = React.useMemo(
        () => [
            {
                label: 'Series 1',
                data: [["15-11-2019", 25], ["16-11-2019", 35], ["17-11-2019",40], ["18-11-2019", 20], ["19-11-2019", 15]]
            }],
        []
    )

    const axes = React.useMemo(
        () => [
            { primary: true, type: 'linear', position: 'bottom' },
            { type: 'linear', position: 'left' },
        ],
        []
    )

    const options = React.useMemo(
        () => [
            {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    unit: 'day'
                }
            }]
        }
    }
        ],
        []
    )

    return (
        // A react-chart hyper-responsively and continuusly fills the available
        // space of its parent element automatically
        <div
            style={{
                width: '600px',
                height: '500px'
            }}
        >
            <Chart data={data} axes={axes} options={options}/>
        </div>
    )
}

export default MyChart;

我的图表

标签: javascriptreactjs

解决方案


更新:请参阅文档中有关格式的这一特定行

使用时间刻度时,可以通过 t 或 x 属性另外指定 x 轴数据点。在此处查看更多信息https://www.chartjs.org/docs/latest/axes/cartesian/time.html

您的数据字段必须是 x、y 值的字典/对象:

data: [{x: "2019-01-03", y: 15}, {x: "2019-01-04", y: 18}, ...]

创建图表时,type设置options.scales

...,
options: {
 scales: {
  xAxes: [{
   type: 'time',
  }]
},
...

推荐阅读