1
votes

If you take a normal bar chart from c3js, the bars will be centered at the x-tick position. I have a chart which goes hourly, so any timespan between 00-24 (usually like 8-16). If I have a line-chart or scatter plot it will align it self exactly on the x-tick nicely, but not as a step-chart or a bar chart.

var chart = c3.generate({
    data: {
            x: 'x',
        columns: [
                ['x', 8, 9, 10, 11, 12, 13, 14, 15, 16],
            ['data1', 1, 1, 0, 1, 0, 0, 1, 1, 1],
        ],
        type: "bar"
    }, 
    axis: {
        x: {
        type: "category",
        categories: [],
      }
    }
});

See this fiddle: https://jsfiddle.net/jvcarphe/1/

I've been trying with all sorts of culling / tick values / time series etc. but I can't for the love of god figure out how to do it. If the type in the fiddle is changed to "line" it does exactly what I want, beside it's not a bar.

1

1 Answers

0
votes

I've had to do this before and there doesn't seem to be a simple setting that does it, but a bit of d3 manipulation works. I came to the conclusion it's easier to move the ticks than the bars:

If you know the width of your bar, you can set a css rule to offset the ticks, just change the -10px to whatever is necessary -->

.c3-axis-x .tick line, .c3-axis-x .tick text {
  transform: translate(-10px,0);
}

(can't just apply the rule to .tick as c3 overrides its transform style)

If you don't know the width then you need to find it out by querying one of the bars and applying the same style rule dynamically in c3's onrendered callback:

onrendered: function () {
        var thisChart = d3.select(this.config.bindto);
        var barWidth = thisChart.select(".c3-bar-0").node().getBoundingClientRect().width / 2;
        thisChart.selectAll(".c3-axis-x .tick line,.c3-axis-x .tick text").style("transform", "translate(-"+barWidth+"px,0)");
}

Fiddle edited as newer version of c3 didn't work in the fiddle:

https://jsfiddle.net/15w50f06/4/