我经常在GNU R / ggplot中为一些与字节相关的测量绘制图形。内置的坐标轴标签通常是普通数字或科学计数法,例如1兆字节= 1e6。我希望使用SI前缀(千= 1e3,兆= 1e6,吉= 1e9等)替代它们,即坐标应该标记为1.5K、5K、1M、150M、4G等。
我目前使用以下代码:
si_num <- function (x) {
if (!is.na(x)) {
if (x > 1e6) {
chrs <- strsplit(format(x, scientific=12), split="")[[1]];
rem <- chrs[seq(1,length(chrs)-6)];
rem <- append(rem, "M");
}
else if (x > 1e3) {
chrs <- strsplit(format(x, scientific=12), split="")[[1]];
rem <- chrs[seq(1,length(chrs)-3)];
rem <- append(rem, "K");
}
else {
return(x);
}
return(paste(rem, sep="", collapse=""));
}
else return(NA);
}
si_vec <- function(x) {
sapply(x, FUN=si_num);
}
library("ggplot2");
bytes=2^seq(0,20) + rnorm(21, 4, 2);
time=bytes/(1e4 + rnorm(21, 100, 3)) + 8;
my_data = data.frame(time, bytes);
p <- ggplot(data=my_data, aes(x=bytes, y=time)) +
geom_point() +
geom_line() +
scale_x_log10("Message Size [Byte]", labels=si_vec) +
scale_y_continuous("Round-Trip-Time [us]");
p;
我想知道这个解决方案能否得到改进,因为我的方法在每个图表中需要大量的样板代码。
utils:::print.object_size
。 - James