如何在 y 轴上将数据显示为 KB、MB、GB、TB

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

本文关键字:KB MB TB GB 显示 数据      更新时间:2023-09-26

我正在绘制一个图表,显示服务器上的流量。我想在 y 轴上将单位显示为 KB、MB 等。任何意见,我如何通过 d3 轴刻度做到这一点。

您可以使用

d3.tickFormat函数:演示。

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

不过,您还需要对tickValues使用自己的值。