user2075371 user2075371 - 1 year ago 250
Javascript Question

c3 js: How can I group by Year on the X-axis labels?

Using c3 js library for charts ( 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) chart with quarterly grouped by year

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'

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';
label +='%Y';
return label;

Answer Source

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
            return 'Q' + parseInt(d.getMonth() / 3 + 1);

where x is the date labels array

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 =;
    if (!isNaN(Number(tspan.text())))
        tspan.attr('dy', '2em')
        tspan.attr('dy', '0.5em')

where chart is the ID of the chart container

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 {

Fiddle -

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.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download