I am plotting data on a log-transformed axis, and the default in ggplot is to use the exponent for the tick labels. However, I would like to include the base e so that tick labels appear as "e^n". Does anyone know how I can do this? I can find solutions for base 10 exponents (e.g. Pretty axis labels for log scale in ggplot), but not for base e. I've tried modifying the base 10 solution to get base e exponents, but it's not working for me.
This example shows the default behavior:
library(ggplot2)
df <- data.frame(x=c(10, 100), y=c(400, 23000))
ggplot(df, aes(x=x, y=log(y)))+geom_line()
I can express the tick labels in scientific format using
ggplot(df, aes(x=x, y=log(y)))+geom_line()+scale_y_continuous(label=scientific)
but I instead want these labels to appear as e^n
. Can anyone point me in the right direction here?
EDIT: Didzis's solution worked perfectly, but when using a smaller y-range such as this
df <- data.frame(x=c(10, 100), y=c(400, 3000))
the ticks are coming up as decimals (e.g. e^6.5) instead of integers (e.g. e^6, e^7). How can I force ggplot to use just integers? I've tried
ggplot(df, aes(x=x, y=y))+geom_line()+
+ scale_y_continuous(trans="log",breaks = trans_breaks("log", function(x) exp(x), by=1),
+ labels = trans_format("log", math_format(e^.x)))
but that did not work.
EDIT2: I was able to solve this by setting the number of breaks using:
ggplot(df, aes(x=x, y=y))+geom_line()+
scale_y_continuous(trans="log",breaks = trans_breaks("log", function(x) exp(x), n=3),
labels = trans_format("log", math_format(e^.x)))
To get e^n
as labels used scale_y_continuos()
and then use trans_breaks()
and trans_format()
from library scales
to get desired labels. Also to get log scale use argument trans="log"
inside the scales_...
function (do not take log()
of data inside the aes()
).
library(scales)
ggplot(df, aes(x=x, y=y))+geom_line()+
scale_y_continuous(trans="log",breaks = trans_breaks("log", function(x) exp(x)),
labels = trans_format("log", math_format(e^.x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With