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

标签 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=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"))

enter image description here

但是,我需要为 y 轴中的数字使用 SI 前缀表示法,以便我执行以下步骤,
library("sos")

在 sitools 包中使用 findFn
findFn("{SI prefix}") 

然后我使用标签中的 f2si 将浮点数转换为带有 SI 前缀的数字
plt2 <- plt + scale_y_continuous(labels=f2si)

结果图如下所示,

enter image description here

虽然 f2si 将 -1e^-0.8 的 y 轴准确地更改为 -10 n,但它并没有准确显示 0 和 1e^-0.8 的值,它们分别为 0 和 10 n。有人可以建议在这里应该更正什么,以便数字显示为它们应该贯穿始终。

谢谢。

最佳答案

我无法重现您的行为。看到这个:

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)

enter image description here

我也有found另一个类似的功能,如果你不喜欢“0 n”标签:
  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())

enter image description here

关于r - 如何在 R 中使用 ggplot2 绘制的图的 y 轴刻度中准确显示数字的 SI 前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21045545/

相关文章:

r - 通过行列索引替换数据框中的值时如何避免循环?

architecture - 在命名空间中分组与为类添加前缀

ruby-on-rails - 服务器前缀和 rails 路由

r - 在 R ggplot 中的堆叠条形图顶部添加总计数

r - 如果 ggplot2 箱线图中存在多个异常值,则出现抖动

r - 如何在热图的一个图 block 上显示两个分类变量 - 三角形图 block

c# - 使用 Irony 实现前缀表示法表达式解析器

mysql - 在 R 中运行 MySQL 查询,其中要搜索的值在 DF 中

regex - 我无法在 R 中转义反斜杠

r - 如何用单个值替换数据框中每行的最大值