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

北慕城南 提交于 2019-12-06 09:22:41

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

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 = d3.select(d);
    if (!isNaN(Number(tspan.text())))
        tspan.attr('dy', '2em')
    else
        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 {
    display:none;
}

Fiddle - http://jsfiddle.net/rg082b19/

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.


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!