将对数刻度ggplot2上的轴标签格式化为x * 10 ^ y

时间:2019-08-28 23:21:51

标签: r ggplot2

(这是对漂亮格式化对数刻度标签的另一个问题的扩展-Pretty axis labels for log scale in ggplot

我用scale_y_log10()制作ggplot对数刻度,并得到轴标签为1e + 5,1e + 6 ..我想用* 10替换e以得到1x10 ^ 5,1x10 ^ 6 .. < / p>

我找到了解决问题的方法,但寻找一种更简单的方法,只是出于好奇心(请继续阅读)

建议的解决方案1是(https://stackoverflow.com/a/15178139/9049673)并带有示例数据

df <- tibble(x = 1:3, y = c(1e4,1e4.5,3e5.2))
ggplot(df,aes(x,y)) + geom_point() + scale_y_log10(labels = trans_format("log10", math_format(10^.x)))

但这会绘制10的非整数幂,而不是更简单的写法(例如:10 ^ 4.301而不是2 x 10 ^ 4)

我遇到的另一个解决方案是使用正则表达式来更改格式(https://groups.google.com/forum/#!topic/ggplot2/a_xhMoQyxZ4How do I change the formatting of numbers on an axis with ggplot?

fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# 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) 

这可行,但是有没有更简单的方法可以通过更改math_format(10^.x)函数来实现相同功能?

0 个答案:

没有答案