While plotting histogarm, scatterplots and other plots with axes scaled to logarithmic scale in R, how is it possible to use labels such as 10^-1 10^0 10^1 10^2 10^3 and so on instead of the axes showing just -1, 0, 1, 2, 3 etc. What parameters should be added to the commands such as hist(), plot() etc?
Asked
Active
Viewed 2.6k times
18
-
1ggplot2 does this automatically if you do the log transformation within ggplot2. See the examples towards the bottom of this page: http://had.co.nz/ggplot2/geom_boxplot.html – Ari B. Friedman Aug 01 '11 at 10:58
-
Thanks, this helped me out. Also, I found something very useful here as well http://r.789695.n4.nabble.com/log-y-axis-of-histogram-td2399498.html – user744121 Aug 01 '11 at 12:02
3 Answers
22
Apart from the solution of ggplot2 (see gsk3's comment), I would like to add that this happens automatically in plot() as well when using the correct arguments, eg :
x <- 1:10
y <- exp(1:10)
plot(x,y,log="y")
You can use the parameter log="x"
for the X axis, or log="xy"
for both.
If you want to format the numbers, or you have the data in log format, you can do a workaround using axis(). Some interesting functions :
axTicks(x)
gives you the location of the ticks on the X-axis (x=1) or Y-axis (x=2)bquote()
converts expressions to language, but can replace a variable with its value. More information onbquote()
in the question Latex and variables in plot label in R? .as.expression()
makes the language object coming frombquote()
an expression. This allowsaxis()
to do the formatting as explained in?plotmath
. It can't do so with language objects.
An example for nice formatting :
x <- y <- 1:10
plot(x,y,yaxt="n")
aty <- axTicks(2)
labels <- sapply(aty,function(i)
as.expression(bquote(10^ .(i)))
)
axis(2,at=aty,labels=labels)
Which gives

Community
- 1
- 1

Joris Meys
- 106,551
- 31
- 221
- 263
-
Thanks, this is quite useful and I think its a general solution. Worked for me just fine – user744121 Aug 01 '11 at 12:04
17
Here is a different way to draw this type of axis:
plot(NA, xlim=c(0,10), ylim=c(1, 10^4), xlab="x", ylab="y", log="y", yaxt="n")
at.y <- outer(1:9, 10^(0:4))
lab.y <- ifelse(log10(at.y) %% 1 == 0, at.y, NA)
axis(2, at=at.y, labels=lab.y, las=1)
EDIT: This is also solved in latticeExtra
with scale.components

mrbrich
- 853
- 1
- 8
- 9
2
In ggplot2 you just can add a
... +
scale_x_log10() +
scale_y_log10(limits = c(1e-4,1), breaks=c(1e-4,1e-3,1e-2,0.1,1)) + ...
to scale your axis, Label them and add custom breaks.

Benvorth
- 7,416
- 8
- 49
- 70