简体   繁体   中英

ChartJS - Draw chart with label by month, data by day

I'd like to draw a line chart by Chartjs with data by day, but label by month.

If label is displayed by day, then there are a lot of points. So, I'd like to display label by month instead of by day. For example:

在此处输入图片说明

Someone could teach me how to do that?

Thank you.

Just config your xAxes->time property as:
unit: 'month'

xAxes: [{
  type: 'time',
  position: 'bottom',
  time: {
    displayFormats: {'day': 'MM/YY'},
    tooltipFormat: 'DD/MM/YY',
    unit: 'month',
   }
}],

The labels array and the data array have to match. Therefore what you will need to do is calculate your values to be hold in data array in to match your labels

data: {
    labels: ["Jan", "Feb", "March", ...],
    datasets: [{
        label: '# of Votes',
        data: [01, 02, 03, ...],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            ...
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            ...
        ],
        borderWidth: 1
    }]
},

Does that solve your doubt?

This question is quite old now, but I have found a workaround using the afterTickToLabelConversion functionnality. I formatted the date, and left only one label for every month (the rest of the labels are transformed to empty quotes).
Here is the snippet to put in your graph option :

scales: {
        xAxes: [{
            type: 'time',
            position: 'bottom',
            time: {
                displayFormats: {
                    'day': 'MM/YY'
                },
                tooltipFormat: 'DD/MM/YY',
                unit: 'day',
            },
            // leave only one label per month
            afterTickToLabelConversion: function (data) {
                var xLabels = data.ticks;
                var oldLabel = "";
                xLabels.forEach(function (labels, i) {
                    if(xLabels[i] == oldLabel){
                        xLabels[i] = "";
                    } else {
                        oldLabel = xLabels[i];
                    }
                });
            }
        }]
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM