R scientific notation in plots

*爱你&永不变心* 提交于 2019-12-04 04:25:52

This is sort of a hacky way, but there's nothing wrong with it:

plot(x,y/1e3, ylab="y /10^3")

A similar technique is to use eaxis (extended / engineering axis) from the sfsmisc package.

It works like this:

library(sfsmisc)

x <- c(482563, 922167, 4462665)
y <- c(102, 258, 2314)

plot(x, y, xaxt="n", yaxt="n")

eaxis(1)  # x-axis
eaxis(2)  # y-axis

How you get the labels onto your axis depends upon the used plotting system.(base, ggplot2 or lattice) You can use functions from scales package to format your axis numbers:

library(scales)
x <- 10 ^ (1:10)
scientific_format(1)(x)
[1] "1e+01" "1e+02" "1e+03" "1e+04" "1e+05" "1e+06" "1e+07" "1e+08" "1e+09" "1e+10"

Here an example using ggplot2 :

library(ggplot2)
dat <- data.frame(x  = c(102, 258, 2314),                                                                     
                  y  = c(482563, 922167, 4462665))

qplot(data=dat,x=x,y=y) + 
  scale_y_continuous(label=scientific_format(digits=1))+ 
  theme(axis.text.y =element_text(size=50))

EDIT The OP has a specific need. Here some ideas I used here in order to accomplish this :

  1. You can customize your plot labels using axis function.
  2. Use mtext to put text in the outer plot region
  3. Use expression to profit from the plotmath features...

y <- c(102, 258, 2314)                                                                         
x <- c(482563, 922167, 4462665)
plot(x,y,ylab='',yaxt='n')
mtext(expression(10^3),adj=0,padj=-1,outer=FALSE)
axis(side=2,at=y,labels=round(y/1000,2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!