c3 js:我如何按年份在X轴标签上分组?

use*_*371 2 javascript charts labels c3

使用c3 js库获取图表(c3js.org).我试图获得类似于这个图表的东西(即,在Q1,Q2,Q3,Q4之后的2011年,2012年,2013年分别添加年份标签)按季度分组的图表

var chart = c3.generate({
data: {
    x: 'x',
    columns: [
        ['x', '2013-01-01', '2013-01-02', '2013-01-03', '2014-01-04', '2014-01-05', '2014-01-06'],
        ['data1', 30, 200, 100, 400, 150, 250],
        ['data2', 130, 340, 200, 500, 250, 350]
    ]
},
axis: {
    x: {
        type: 'timeseries',
        tick: {
            format: '%Y-%m-%d'
        }
    }
}
});
Run Code Online (Sandbox Code Playgroud)

以年 - 月 - 日格式显示每个标签中带有年份的x轴.我想在标签的第一行显示月份和日期,在下一行显示年份(不重复).有一些像:

format: function(){
     var label = '%m-%d';
     if(year!written)
           label +='%Y';
     return label;
}
Run Code Online (Sandbox Code Playgroud)

pot*_*ngs 9

您可以使用刻度格式来编写标签

...
tick: {
    culling: false,
    count: (x.length - 1) * 2 - 1,
    format: function (d) {
        // show the year in place of Jul
        if (d.getMonth() === 6)
            return d.getFullYear();
        // ignore other non quarter months
        else if ([1, 4, 7, 10].indexOf(d.getMonth()) === -1)
            return '';
        // quarter months
        else
            return 'Q' + parseInt(d.getMonth() / 3 + 1);
    }
}
...
Run Code Online (Sandbox Code Playgroud)

其中x是日期标签数组


然后使用d3选择并按下年份标签

// push the years down
d3.selectAll('#chart .tick text tspan')[0].forEach(function (d) {
    var tspan = d3.select(d);
    if (!isNaN(Number(tspan.text())))
        tspan.attr('dy', '2em')
    else
        tspan.attr('dy', '0.5em')
})
Run Code Online (Sandbox Code Playgroud)

where表chart是图表容器的ID


最后隐藏所有刻度线(或者你可以使用CSS类型n选择器隐藏/显示你不想要的那些)

#chart .tick line {
    display:none;
}
Run Code Online (Sandbox Code Playgroud)

小提琴 - http://jsfiddle.net/rg082b19/

我有间歇性的问题,小提琴没有在你跑步时推倒标签,但这不会发生在小提琴之外.因此,如果您没有看到轴标签向下移动,只需将代码复制到本地HTML文件中即可.


在此输入图像描述