坐标轴的数字特别大,很多0,又不想改成log10的显示方式时,可以改为10的N次方。
注:此方法基础代码来源于:https://groups.google.com/g/ggplot2/c/a_xhMoQyxZ4中Brian Diggs;
修改部分来源于:https://stackoverflow.com/questions/11610377/how-do-i-change-the-formatting-of-numbers-on-an-axis-with-ggplot/24241954#24241954中第一条回复里semi-extrinsic和John_West的评论。
格式设置的完整代码如下:
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
l <- gsub("0e\\+00","0",l)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# remove "+" after exponent, if exists. E.g.: (3x10^+2 -> 3x10^2)
l <- gsub("e\\+","e",l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# convert 1x10^ or 1.000x10^ -> 10^
l <- gsub("\\'1[\\.0]*\\'\\%\\*\\%", "", l)
# return this as an expression
parse(text=l)
}
然后就可以直接用了:
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)