[英]How to accurately display SI prefix for numbers in y-axis scale of plot made with ggplot2 in R?
我有以下圖,使用此代碼生成
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"))
但是我需要在y軸上的數字使用SI前綴表示法,為了得到我做了以下步驟,
library("sos")
在sitools包中使用findFn
findFn("{SI prefix}")
然后我使用標簽中的f2si將浮點數編號轉換為帶有SI前綴的數字
plt2 <- plt + scale_y_continuous(labels=f2si)
結果情節看起來像這樣,
當f2si精確地將y軸改變為-1e ^ -0.8到-10n時,它不能准確地顯示0和1e ^ -0.8的值,它們分別為0和10n。 有人可以建議在這里應該糾正什么,以便數字顯示在它們應該貫穿始終。
謝謝。
我無法重現你的行為。 看到這個:
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)
我還發現了另一個類似的功能,如果你不喜歡“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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.