R ggplot2轴标签中的SI前缀

R ggplot2轴标签中的SI前缀,r,ggplot2,R,Ggplot2,我经常在GNU R/ggplot中绘制一些与字节相关的度量值的图形。内置轴标签为普通数字或科学符号,即1兆字节=1e6。我希望使用SI前缀(Kilo=1e3、Mega=1e6、Giga=1e9等),即轴应标记为1.5K、5K、1M、150M、4G等 我目前使用以下代码: si_num <- function (x) { if (!is.na(x)) { if (x > 1e6) { chrs <- strsplit(format(x, scienti

我经常在GNU R/ggplot中绘制一些与字节相关的度量值的图形。内置轴标签为普通数字或科学符号,即1兆字节=1e6。我希望使用SI前缀(Kilo=1e3、Mega=1e6、Giga=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;
si_num 1e6){
chrs我使用
library(“sos”);findFn(“{SI prefix}”)
来查找
sitools

构造数据:

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=f2si) +
     scale_y_continuous("Round-Trip-Time [us]"))

(p更新:该软件包的最新版本包括打印可读标签的功能

在这种情况下,可以使用:

库(ggplot2)
图书馆(比例尺)

可以查看的字节数
utils:::print.object\u size
(p <- ggplot(data=my_data, aes(x=bytes, y=time)) +
     geom_point() +
     geom_line() +
     scale_x_log10("Message Size [Byte]", labels=f2si) +
     scale_y_continuous("Round-Trip-Time [us]"))
si_format <- function(...) {
    function(x) f2si(x,...)
}