简体   繁体   English

ChartJS - 按月绘制带标签的图表,按天绘制数据

[英]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.我想用Chartjs按天绘制折线图,​​但按月标记。

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:只需将您的 xAxes->time 属性配置为:
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. labels数组和data数组必须匹配。 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.这个问题现在已经很老了,但我找到了使用afterTickToLabelConversion功能的解决方法。 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];
                    }
                });
            }
        }]
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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