c3 js:如何在X轴标签上按年份分组? [英] c3 js: How can I group by Year on the X-axis labels?

查看:263
本文介绍了c3 js:如何在X轴标签上按年份分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c3 js库获取图表(c3js.org).我正在尝试实现与该图表类似的功能(即在第1季度,第2季度,第3季度,第4季度之后的单独一行上添加年份标签2011、2012、2013)

Using c3 js library for charts (c3js.org). I'am trying to achieve something similar to this chart (i.e., add year label 2011, 2012, 2013 on a seperate line after Q1, Q2, Q3, Q4)

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'
        }
    }
}
});

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

show's the x axis with year in each label in the format year-month-day. I want to show just the month and date on first line of label and the year in the next line (without repetition). Kind of like:

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

推荐答案

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

You can do this using the tick format to write the labels

...
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);
    }
}
...

其中x是日期标签数组

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

Then using d3 to select and push the year labels a bit down

// 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')
})

其中chart是图表容器的ID

where chart is the ID of the chart container

最后隐藏所有刻度线(或者您可以使用CSS nth-of-type选择器隐藏/显示不想要的标记)

And finally hiding all the tick marks (or you could use the CSS nth-of-type selector to hide / show the ones you don't want)

#chart .tick line {
    display:none;
}


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

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

I'm having intermittent problems with the Fiddle not pushing the labels down when you Run, but that doesn't happen outside of the fiddle. So if you don't see the axis labels moving down, just copy the code into a local HTML file and it will work.

这篇关于c3 js:如何在X轴标签上按年份分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆