Adding a Date adapter for Time Cartesian axis from a cdn

Viewed 1246

I wanted to create a graph which contains a Time Cartesian axis. The docs tell me that I need to use an adapter for a type: 'time' axis. I chose chartjs-adapter-date-fns, and imported it using the following cdn:

<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

Now the docs tell me an object must be passed as the adapters.date property of an axis id. But which class/object should I put there? I'm stuck here. Can anyone point me in the right direction?

I'm using ChartJS 3.4.1 and Chartisan.

                      x: {
                            adapters: { 
                                date: { 
                                    // Adapter object here.
                                }
                            },
                            type: 'time',
                            time: {
                                unit: 'day'
                            },
                        },

Many thanks in advance!

3 Answers

The documentation for chartjs-adapter-date-fns states:

date-fns requires a date-fns locale object to be tagged on to each format() call, which requires the locale to be explicitly set via the adapters.date option

And gives the following example:

// import date-fns locale:
import {de} from 'date-fns/locale';

// scale options:
{
    adapters: {
        date: {
            locale: de
        }
    }
}

Hopefully not too late, but just in case: I grappled with this, too, and in the end found that you can simply feed chartjs with time scale integers as x values. Convert your timestamps to seconds since the epoch and multiply by 1000, because js uses milliseconds whereas unix uses seconds.

My code is in python, so I convert the timestamp string to milliseconds since the epoch, fist:

# get data from backend   
hist = self.backend_get(f"/{name}/history")     
# convert format for chart, filter out None
data_l = [{'x' : 1000*int(datetime.fromisoformat(d['timestamp']).strftime('%s')), 
                   'y' : d['value']} for d in hist if d['value'] is not None]
label = "<insert your label>"

Now construct the data

        data = {
            'type': 'line',
            'data': {
                'labels': [],
                'datasets': [{
                    'label': label,
                    'data': data_l,
                    }]
                },
            'options': {
                'scales': {
                    'x': {
                        'type': 'time',
                        'time': {'unit': 'day'},
                    },
                },
            },
        }

Finally insert the charts js and canvas into the html:

        html_s += '''
            <div>
              <canvas id="myChart" class="history_canvas"></canvas>
            </div>
            <script>
                var ctx = document.getElementById('myChart');
                var myChart = new Chart(ctx, 
        '''
        html_s += f'{data}'
        html_s += '''
                );
            </script>
            <h3>Raw data</h3>         
        '''        

time scale data using ms since epoch as x values

PS I think this only works in Unix because of the epoch.

Nevermind, just adding the cdn was sufficient. The problem was that the labels weren't in date format but in relative time instead ("2 hours ago" instead of 20-07-2021)

Related