gpt4 book ai didi

r - ggplot2 轴标签中的 SI 前缀

转载 作者:行者123 更新时间:2023-12-02 17:59:40 27 4
gpt4 key购买 nike

我经常在 GNU R/ggplot 中绘制一些与字节相关的测量图表。内置轴标签可以是普通数字或科学记数法,即 1 MB = 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;

我想知道这个解决方案是否可以改进,因为我的解决方案在每个图中都需要大量样板代码。

最佳答案

我使用了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)

加载包:

library("sitools")
library("ggplot2")

创建情节:

(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]"))

我不确定这与你的函数相比如何,但至少其他人不厌其烦地编写了它......

我稍微修改了你的代码风格——行尾的分号是无害的,但通常是 MATLAB 或 C 编码器的标志......

编辑:我最初定义了一个通用格式化函数

si_format <- function(...) {
function(x) f2si(x,...)
}

遵循(例如)scales::comma_format 的格式,但在本例中这似乎是不必要的——只是我不知道的更深层的ggplot2魔法的一部分完全理解。

OP的代码给出了在我看来不太正确的答案:最右边的轴刻度是“1000K”而不是“1M”——这可以通过更改>1e6来解决测试>=1e6。另一方面,f2si使用小写的k——我不知道是否需要K(将结果包装在 >toupper() 可以解决这个问题)。

OP结果(si_vec):

enter image description here

我的结果(f2si):

enter image description here

关于r - ggplot2 轴标签中的 SI 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com