Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart js x-axis values getting repeated twice

I'm using the following code to generate a line chart using chart js plugin, in which I'm facing the problem where the x-axis values are repeated twice.

function newDate(days) {
    return moment().add(days, 'd').format('MM/DD');
}

var painChartContext = document.getElementById('pain_chart');
    var painChart = new Chart(painChartContext, {
        type: 'line',
        data: {
            labels: [newDate(-7), newDate(-6), newDate(-5), newDate(-4), newDate(-3), newDate(-2), newDate(-1)],
            datasets: [{
                label: "Pain",
                data: [8, 9, 7, 3, 10, 3, 4],
                fill: false,
                borderColor: '#b71705',
                spanGaps: true
            }]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        displayFormats: {
                            'millisecond': 'MM/DD',
                            'second': 'MM/DD',
                            'minute': 'MM/DD',
                            'hour': 'MM/DD',
                            'day': 'MM/DD',
                            'week': 'MM/DD',
                            'month': 'MM/DD',
                            'quarter': 'MM/DD',
                            'year': 'MM/DD',
                        },
                        min: '04/13',
                        max: '04/19'
                    }                 
                }],
            },
        }
    });

As I mentioned above this gives me the following chart, where x-axis date values are repeating twice.enter image description here

Also in my console, I'm getting a warning message about moment js;

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.

which I think is because of this line of code;

function newDate(days) {
    return moment().add(days, 'd').format('MM/DD');
}

Kindly anyone give me a solution for this, thanks.

like image 630
karthi Avatar asked Apr 20 '17 07:04

karthi


1 Answers

So chartjs is creating the x-axis labels dynamically and decided it can show two labels per day, which when formatted end up showing two dates that are the same.

Pass a new field unit to the time object and set it to day. this will cause the chart to only show one tick per day in the time frame. (example fiddle)

options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                     unit: 'day',
                }                 
            }],
        },
    }
like image 158
Quince Avatar answered Oct 19 '22 04:10

Quince