如何使用 ggplot2 和比例使用指数格式化轴标签? [英] How can I format axis labels with exponents with ggplot2 and scales?
问题描述
使用新版本的 ggplot2 和 scales,我无法弄清楚如何以科学记数法获取轴标签.例如:
With the new version ggplot2 and scales, I can't figure out how to get axis label in scientific notation. For example:
x <- 1:4
y <- c(0, 0.0001, 0.0002, 0.0003)
dd <- data.frame(x, y)
ggplot(dd, aes(x, y)) + geom_point()
给我
我希望轴标签为 0、5 x 10^-5、1 x 10^-4、1.5 x 10^-4 等.我无法弄清楚 的正确组合scale_y_continuous()
和 math_format()
(至少我认为这些是我需要的).
I'd like the axis labels to be 0, 5 x 10^-5, 1 x 10^-4, 1.5 x 10^-4, etc. I can't figure out the correct combination of scale_y_continuous()
and math_format()
(at least I think those are what I need).
scale_y_log10()
日志转换轴,这是我不想要的.scale_y_continuous(label = math_format())
只给我 10^0、10^5e-5 等.我明白为什么后者会给出那个结果,但这不是我想要的.
scale_y_log10()
log transforms the axis, which I don't want. scale_y_continuous(label = math_format())
just gives me 10^0, 10^5e-5, etc. I see why the latter gives that result, but it's not what I'm looking for.
我正在使用 ggplot2_0.9.1 和 scales_0.2.1
I am using ggplot2_0.9.1 and scales_0.2.1
推荐答案
我改编了 Brian 的回答,我想我得到了你想要的.
I adapted Brian's answer and I think I got what you're after.
只需将 parse() 添加到 science_10() 函数(并将x"更改为正确的时间"符号),您就可以得到这样的结果:
Simply by adding a parse() to the scientific_10() function (and changing 'x' to the correct 'times' symbol), you end up with this:
x <- 1:4
y <- c(0, 0.0001, 0.0002, 0.0003)
dd <- data.frame(x, y)
scientific_10 <- function(x) {
parse(text=gsub("e", " %*% 10^", scales::scientific_format()(x)))
}
ggplot(dd, aes(x, y)) + geom_point()+scale_y_continuous(label=scientific_10)
您可能仍然希望改进该函数,以便更优雅地处理 0,但我认为就是这样!
You might still want to smarten up the function so it deals with 0 a little more elegantly, but I think that's it!
这篇关于如何使用 ggplot2 和比例使用指数格式化轴标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!