Magofoco
Magofoco

Reputation: 5446

Chart.js x-axis with date DD-MM-YYYY - React

I am trying to display a graph using the library Chart.js.

My data are in the format:

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

I am not able to transform the x-Axis in a time-axis.

I tried to pass in the options parameter the time type but it does not seem to work. The graph renders, but the x-axis does not exists, only the y-axis exists.

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;

MyGraph

Upvotes: 1

Views: 8220

Answers (1)

ege
ege

Reputation: 774

Update: See this specific line about format in the documentation

The x-axis data points may additionally be specified via the t or x attribute when using the time scale. See more here https://www.chartjs.org/docs/latest/axes/cartesian/time.html

Your datafield must be a dictionary/object of x, y values:

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

When creating your chart, set type in options.scales:

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

Upvotes: 3

Related Questions