如何使用带有ggplot2和比例的指数格式化轴标签?

kmm*_*kmm 20 r ggplot2

使用新版ggplot2和scale,我无法弄清楚如何以科学计数法获得轴标签.例如:

x <- 1:4
y <- c(0, 0.0001, 0.0002, 0.0003)

dd <- data.frame(x, y)

ggplot(dd, aes(x, y)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

给我

带刻度的ggplot示例

我想轴标签是0,5 x 10 ^ -5,1 x 10 ^ -4,1.5 x 10 ^ -4等.我无法弄清楚正确的组合scale_y_continuous()math_format()(至少我认为那些是我需要的).

scale_y_log10()日志转换轴,我不想要.scale_y_continuous(label = math_format())只给我10 ^ 0,10 ^ 5e-5等等.我明白为什么后者给出了这个结果,但这不是我想要的.

我正在使用ggplot2_0.9.1和scales_0.2.1

Tom*_*ant 33

我改编了Brian的答案,我想我得到了你想要的东西.

只需在scientific_10()函数中添加一个parse()(并将'x'更改为正确的'times'符号),您最终会得到:

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你可能仍然希望智能化这个功能,所以它更优雅地处理0,但我认为就是这样!


com*_*ver 21

根据对已接受的解决方案的评论,OP希望将指数格式化为指数.这可以通过scale包中的trans_formattrans_breaks函数来完成:

    library(ggplot2)
    library(scales)

    x <- 1:4
    y <- c(0, 0.0001, 0.0002, 0.0003)
    dd <- data.frame(x, y)

    ggplot(dd, aes(x, y)) + geom_point() +
    scale_y_log10("y",
        breaks = trans_breaks("log10", function(x) 10^x),
        labels = trans_format("log10", math_format(10^.x)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Bri*_*ggs 11

scale_y_continuous(label=scientific_format())
Run Code Online (Sandbox Code Playgroud)

给出带有e而不是10的标签:

在此输入图像描述

我想如果你真的想要10个,那么你可以将它包装在另一个函数中.

scientific_10 <- function(x) {
  gsub("e", " x 10^", scientific_format()(x))
}

ggplot(dd, aes(x, y)) + geom_point() + 
  scale_y_continuous(label=scientific_10)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


she*_*fly 9

从上面汤姆的回答中取笑,以下内容删除了 + 符号,并更好地处理了 0(该函数也是匿名内联的):

scale_y_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " %*% 10^", scientific_format()(x)))))} ) +
Run Code Online (Sandbox Code Playgroud)


ewa*_*ace 6

我写了一个scientific_10的版本,避免了scales包;它还删除指数中的前导零(10^04 到 10^4 等)。这是根据上面给出的有用答案改编的。

我还在下面包含了包装缩放功能。

scientific_10 <- function(x) {
    xout <- gsub("1e", "10^{", format(x),fixed=TRUE)
    xout <- gsub("{-0", "{-", xout,fixed=TRUE)
    xout <- gsub("{+", "{", xout,fixed=TRUE)
    xout <- gsub("{0", "{", xout,fixed=TRUE)
    xout <- paste(xout,"}",sep="")
    return(parse(text=xout))
}

scale_x_log10nice <- function(name=NULL,omag=seq(-10,20),...) {
    breaks10 <- 10^omag
    scale_x_log10(name,breaks=breaks10,labels=scientific_10(breaks10),...)
}

scale_y_log10nice <- function(name=NULL,omag=seq(-10,20),...) {
    breaks10 <- 10^omag
    scale_y_log10(name,breaks=breaks10,labels=scientific_10(breaks10),...)
}

scale_loglog <- function(...) {
    list(scale_x_log10nice(...),scale_y_log10nice(...))
}

qplot(x=exp(5*rnorm(100)),geom="density",kernel="rectangular") + 
    scale_x_log10nice()
Run Code Online (Sandbox Code Playgroud)