Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display data as KB, MB, GB, TB on y axis

I am drawing a chart which is displaying traffic volume on server. I want to display units as KB, MB etc on y axis. Any opinion how can I do this via d3 axis scales.

like image 733
Dania Avatar asked Feb 15 '23 17:02

Dania


1 Answers

You can do it using the d3.tickFormat function: Demo.

var bytesToString = function (bytes) {
    // One way to write it, not the prettiest way to write it.

    var fmt = d3.format('.0f');
    if (bytes < 1024) {
        return fmt(bytes) + 'B';
    } else if (bytes < 1024 * 1024) {
        return fmt(bytes / 1024) + 'kB';
    } else if (bytes < 1024 * 1024 * 1024) {
        return fmt(bytes / 1024 / 1024) + 'MB';
    } else {
        return fmt(bytes / 1024 / 1024 / 1024) + 'GB';
    }
}

var xScale = d3.scale.log()
               .domain([1, Math.pow(2, 40)])
               .range([0, 480]);

var xAxis = d3.svg.axis()
                .scale(xScale)
                .orient('left')
                .tickFormat(bytesToString)
                .tickValues(d3.range(11).map(
                    function (x) { return Math.pow(2, 4 * x); }
                ));

You will also want to use your own values for the tickValues as well, though.

like image 58
musically_ut Avatar answered Feb 17 '23 11:02

musically_ut