相关疑难解决方法(0)

ggplot2轴标签中的SI前缀

我经常在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 …
Run Code Online (Sandbox Code Playgroud)

r ggplot2

11
推荐指数
2
解决办法
2204
查看次数

如何在R中用ggplot2制作的图的y轴刻度中准确显示数字的SI前缀?

我有以下图,使用此代码生成

plt <- ggplot(d2, aes_string(x=names(same_df)[1],y= "value")) + 
    geom_point(aes(color = variable), size = 1)+ theme_bw()+
    theme(legend.text=element_text(size=14), legend.title=element_text(size=14))+
    theme(axis.text=element_text(size=20)) +
    theme(axis.title=element_text(size=20,face="bold")) + scale_color_discrete(name = "title", labels = c("1", "2", "3", "4","5","6","7","8","9")) + labs(x = "x", y = "y")+ guides(colour = guide_legend(override.aes = list(size=4),ncol=2,title.hjust=0.5))+theme(plot.margin=unit(c(0,0,0,0),"mm"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是我需要在y轴上的数字使用SI前缀表示法,为了得到我做了以下步骤,

library("sos")
Run Code Online (Sandbox Code Playgroud)

在sitools包中使用findFn

findFn("{SI prefix}") 
Run Code Online (Sandbox Code Playgroud)

然后我使用标签中的f2si将浮点数编号转换为带有SI前缀的数字

plt2 <- plt + scale_y_continuous(labels=f2si)
Run Code Online (Sandbox Code Playgroud)

结果情节看起来像这样,

在此输入图像描述

当f2si精确地将y轴改变为-1e ^ -0.8到-10n时,它不能准确地显示0和1e ^ -0.8的值,它们分别为0和10n.有人可以建议在这里应该纠正什么,以便数字显示在它们应该贯穿始终.

谢谢.

r prefix ggplot2

7
推荐指数
1
解决办法
693
查看次数

标签 统计

ggplot2 ×2

r ×2

prefix ×1