Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling number formatting at axis of R plots

Tags:

plot

r

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...

like image 745
David B Avatar asked Aug 05 '10 13:08

David B


People also ask

How do I change axis numbers in R?

Method 1: Change Axis Scales in Base R To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I customize axis labels in R?

Key ggplot2 R functions p + xlab(“New X axis label”): Change the X axis label. p + ylab(“New Y axis label”): Change the Y axis label. p + labs(x = “New X axis label”, y = “New Y axis label”): Change both x and y axis labels.

How do I reduce the size of axis labels in R?

Go to the menu in RStudio and click on Tools and then Global Options. Select the Appearance tab on the left. Again buried in the middle of things is the font size. Change this to 14 or 16 to start with and see what it looks like.


2 Answers

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

like image 57
rcs Avatar answered Nov 15 '22 22:11

rcs


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?!

like image 23
daniel.heydebreck Avatar answered Nov 15 '22 21:11

daniel.heydebreck