如何在R中使用ggplot2绘制的绘图的y轴比例中准确显示数字的SI前缀?

如何在R中使用ggplot2绘制的绘图的y轴比例中准确显示数字的SI前缀?,r,ggplot2,prefix,R,Ggplot2,Prefix,我有下面的图,用这个代码生成 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=elem

我有下面的图,用这个代码生成

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"))
在sitools包中使用findFn

findFn("{SI prefix}") 
然后我使用标签中的f2si将浮点数转换为带有SI前缀的数字

plt2 <- plt + scale_y_continuous(labels=f2si)

plt2我无法重现你的行为。见此:

df <- data.frame(x=runif(100), y=(runif(100)-1/2)/1e8)
p <- ggplot(df, aes(x, y)) + geom_point()
p + scale_y_continuous(labels=f2si)

df-See。谢谢你的建议,它现在可以工作了,我想你的意思是
p+scale\u y\u continuous(labels=format\u-si())
在代码的最后一行中删除接近0的n。我真的很喜欢你写的
format\u-si()
函数,因为它很容易定制,比如用“B”替换“G”来表示数十亿,如果愿意的话。@coip谢谢,我的荣幸。
df <- data.frame(x=runif(100), y=(runif(100)-1/2)/1e8)
p <- ggplot(df, aes(x, y)) + geom_point()
p + scale_y_continuous(labels=f2si)
  format_si <- function(...) {
  # Based on code by Ben Tupper
  # https://stat.ethz.ch/pipermail/r-help/2012-January/299804.html

  function(x) {
    limits <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12,
                1e-9,  1e-6,  1e-3,  1e0,   1e3,
                1e6,   1e9,   1e12,  1e15,  1e18,
                1e21,  1e24)
    prefix <- c("y",   "z",   "a",   "f",   "p",
                "n",   "µ",   "m",   " ",   "k",
                "M",   "G",   "T",   "P",   "E",
                "Z",   "Y")

    # Vector with array indices according to position in intervals
    i <- findInterval(abs(x), limits)

    # Set prefix to " " for very small values < 1e-24
    i <- ifelse(i==0, which(limits == 1e0), i)

    paste(format(round(x/limits[i], 1),
                 trim=TRUE, scientific=FALSE, ...),
          prefix[i])
  }
}

p + scale_y_continuous(labels=format_si())