Royw
Royw

Reputation: 599

C3js change axis time format on load

I have a C3.js chart with time values formatted per minute as %H:%M. Now I want to load new data, but instead of data per hour I want to show the data per day as %d-%m. So the tick format needs to change, but how do I do this?

chart generation with C3.js

  chart = c3.generate({
        bindto: element,
        data: {
            x: "keys",
            xFormat: '%Y-%m-%d %H:%M:%S',
            url: dataurl + '/today',
            mimeType: 'json',
            type: 'bar',

        },
        axis: {
            x: {
                type: 'timeseries',
                tick: {
                    format: '%H:%M'
                }
            }
        }
    });

Loading new data

 chart.load({
        x: "keys",
        xFormat: '%Y-%m-%d %H:%M:%S',
        url: url,
        mimeType: 'json',
    });

Upvotes: 1

Views: 6052

Answers (1)

JasTonAChair
JasTonAChair

Reputation: 1978

Latest from Masayuki on Github - said there was no API for that.

But you can define a global variable to change ticks dynamically, see Masayuki's fiddle

From Github -

var formatter;
function updateFormatter(byMonth) {
  formatter = d3.time.format(byMonth ? '%Y-%m' : '%Y-%m-%d')
}

updateFormatter();

var chart = c3.generate({
    data: {
        x: 'date',     
        columns: [
            ['date', '2014-01-01', '2014-01-02', '2014-01-03'],
            ['data1', 100, 200, 300],
        ]
    },
    axis: {
      x: {
        type: 'timeseries',
        tick: {
            format: function (x) { // x comes in as a time string.
              return formatter(x);
            }
        }
      }
    }
});

d3.select('#btnByMonth').on('click', function () {
  updateFormatter(true);
  chart.flush();            
});
d3.select('#btnByWeek').on('click', function () {
  updateFormatter(false);
  chart.flush();            
});

Upvotes: 7

Related Questions