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.00
Riffing off of Tom's answer above, the following removes + signs, and handles 0 better (the function is anonymously inlined as well):
scale_y_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " %*% 10^", scientific_format()(x)))))} ) +
I adapted Brian's answer and I think I got what you're after.
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)
You might still want to smarten up the function so it deals with 0 a little more elegantly, but I think that's it!
I wrote a version of scientific_10 that avoids the scales package; it also removes leading zeroes in exponents (10^04 to 10^4, etc.). This was adapted from the helpful answers given above.
I've also included wrapper scale functions below.
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()
scale_y_continuous(label=scientific_format())
gives labels with e instead of 10:
I suppose if you really want 10's in there, you could then wrap that in another function.
scientific_10 <- function(x) {
gsub("e", " x 10^", scientific_format()(x))
}
ggplot(dd, aes(x, y)) + geom_point() +
scale_y_continuous(label=scientific_10)
As per the comments on the accepted solution, OP is looking to format exponents as exponents. This can be done with the trans_format
and trans_breaks
functions in the scales package:
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)))