C3 chart - How to set X-Axis a DateTime interval 1 week?

524 Views Asked by At

I am very new to building charts with c3. I've done a search, but I could not find an answer. Could anyone help?

How can I force to set in X-Axis a DateTime interval of 1 week, if my dates start with 01-Jan-2022 and end with 01-April-2022, then it must start with 01-Jan-2022 and then 07-Jan-2022, 14-Jan-2022, 21-Jan-2022 and so...

var chart = c3.generate({
data: {
    x: 'x',
    columns: [
        ['x', '2022-01-01', '2022-01-07', '2022-01-14', '2022-01-21', '2022-01-28', '2022-02-04', '2022-02-11', '2022-02-18', '2022-02-25'],
        ['data1', 30, 200, 100, 400, 150, 250, 300, 350, 320]
        
    ]
},
axis: {
    x: {
        type: 'timeseries',
        tick: {
            format: '%Y-%m-%d'
        }
    }
}});

Above, I have given one sample example. Here start date is 01-01-2022 and the end date is 25-02-2022. So how can I pass min range is 01-01-2022 and max range is 25-02-2022 with an interval of 1 week

2

There are 2 best solutions below

0
On

c3.js will default to the range of data that is provided, but you can set the x axis tick values separately from the data. Editing your code, here's an example:

var chart = c3.generate({
data: {
    x: 'x',
    columns: [
        ['x', '2022-01-01', '2022-01-07', '2022-01-14', '2022-01-21', '2022-01-28', '2022-02-04', '2022-02-11', '2022-02-18', '2022-02-25'],
        ['data1', 30, 200, 100, 400, 150, 250, 300, 350, 320]
        
    ]
},
axis: {
    x: {
        type: 'timeseries',
        tick: {
            format: '%Y-%m-%d',
            values: ['2022-01-01', '2022-01-07', '2022-01-14', '2022-01-21', '2022-01-28', '2022-02-04', '2022-02-11', '2022-02-18', '2022-02-25'],
            rotate: -30
        }
    }
}});
0
On

As per my understanding, the C3 chart does not provide any built-in function to change X-Axis Interval.

It can be done using the customized logic of x-axis, we have to customize the culling function, see below I want 7 days interval between two dates so I have to customize the below way.

function maxCulling(total_days) {
  const days = total_days;
  const quotient = Math.trunc(days / 7);
  return days % 7 === 0 ? quotient : quotient + 1;
}


var chart = c3.generate({
data: {
    x: 'x',
    columns: [
        ['x', '2022-01-01', '2022-01-07', '2022-01-14', '2022-01-21', '2022-01-28', '2022-02-04', '2022-02-11', '2022-02-18', '2022-02-25'],
        ['data1', 30, 200, 100, 400, 150, 250, 300, 350, 320]
        
    ]
},
axis: {
    x: {
        type: 'timeseries',
        tick: {
            format: '%Y-%m-%d',
            culling: { max: maxCulling(total_dates) },
            rotate: -30
        }
    }
}});