David B
David B

Reputation: 29998

Controlling number formatting at axis of R plots

I have some 100k values. When I plot them as a line in R (using plot(type="l") the numbers next to the x-axis ticks are printed in scientific format (e.g. 0e+00,2e+04,...,1e+05). Instead, I would like them to be:

A) 0,20kb,...,100kb

B) the same but now the first coordinate should be 1 (i.e. starting to count from 1 instead of 0).

BTW R arrays use numbering that starts from 1 (in contrast to arrays in perl, java etc.) so I wonder why when plotting "they" decided starting from 0...

Upvotes: 10

Views: 20288

Answers (2)

daniel.heydebreck
daniel.heydebreck

Reputation: 445

The question is quite old but when I looked for solutions for the described problem it was ranked quite high. Therefore, I add this - quite late - answer and hope that it might help some others :-) .

In some situations it might be useful to use the tick locations which R suggests. R provides the function axTicks for this purpose. Possibly it did not exist in R2.X but only since R3.X.

A)

myTicks = axTicks(1)
axis(1, at = myTicks, labels = paste(formatC(myTicks/1000, format = 'd'), 'kb', sep = ''))

B)

If you plot data like plot(rnorm(1000)), then the first x-value is 1 and not 0. Therefore, numbering automatically starts with 1. Maybe this was a problem with a previous version of R?!

Upvotes: 4

rcs
rcs

Reputation: 68839

A)

R> xpos <- seq(0, 1000, by=100)
R> plot(1:1000, rnorm(1000), type="l", xaxt="n")
R> axis(1, at=xpos, labels=sprintf("%.2fkb", xpos/1000))

B) same as above, adjust xpos

Upvotes: 9

Related Questions