gpt4 book ai didi

javascript - 根据以字节为单位的值,使用 KiB、MiB、GiB 单位设置 d3 轴

转载 作者:行者123 更新时间:2023-11-30 15:00:37 24 4
gpt4 key购买 nike

我有一个跟踪文件大小的图表。我想设置一个显示文件大小的轴 (Y),并带有适当的 Mebibyte 后缀,例如:KiB、MiB、GiB 等。

现在,我以字节为单位输入数据,因此理论上一个简单的 .tickFormat() 方法后跟一个 d3.format() 应该可以解决问题。不幸的是,情况并非如此,因为文件大小实际上是 1024(或 2^20)的倍数,而不是典型的 SI 10^6。这意味着我的线开始绘制,但轴很奇怪。

以文件大小 587108352 为例,如果将其四舍五入到最接近的 MB,我将得到 560MiB(使用 1024 (2^20) 乘数)。

我如何设置我的轴​​来处理它?

我试过这个:

yAxis = d3.axisLeft(y)
.tickFormat(function (d) {
return d3.format(scope.formatOptions.specifier)(d * scope.formatOptions.multiplier) + scope.formatOptions.suffix;
});

格式选项对象在哪里:

vm.FormatObjectSize = {
specifier: ".0s", // decimal notation with an SI prefix, rounded to significant digits.
multiplier: 1, // none
suffix: "b" // bytes
};

这并不是很好:

enter image description here

最佳答案

您可以使用带有转换文件大小功能的tickFormat。在这里,我使用了 this answer 中提供的功能,我将其命名为 fileSize

因此,您的tickFormat 应该是:

.tickFormat(function(d){
return fileSize(d)
}

这是一个演示,从 0587108352:

var scale = d3.scaleLinear()
.domain([0, 587108352])
.range([20, 470]);

var svg = d3.select("svg");

var gX = svg.append("g").attr("transform", "translate(0,50)")
.call(d3.axisBottom(scale).tickValues(scale.ticks(5).concat(scale.domain())).tickFormat(function(d) {
return fileSize(d)
}))

function fileSize(bytes) {
var thresh = 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while (Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1) + ' ' + units[u];
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="100"></svg>

如您所见,587108352 的最后一个值为 559.9 兆字节,这是正确的值。

顺便说一句,你的问题的标题有点不正确:你想要的实际上是 KiB, MiB, GiB 等等,而不是 Kb, Mb, Gb...

此外,可以使用 MB/GB/TB/等或 MiB/GiB/TiB/等提供文件/存储大小,具体取决于具体情况。例如,HD 制造商通常使用十进制 (1000),而 RAM 制造商通常使用 1024。

关于javascript - 根据以字节为单位的值,使用 KiB、MiB、GiB 单位设置 d3 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com