therob therob - 1 year ago 49
R Question

Only label for value "zero" is not centered to its tick in Plot()

I am using normal

in R, and do the label and ticks with the pretty-function for more flexibility (marks...).

But it happens that the label for the value "zero" is not properly aligned (centred) around the corresponding tick, whereas all others are looking OK. (See screenshots linked below.)

  • It only happens, when I use "scientific=FALSE" in format(...)

  • It looks correct, if I use "scientific=TRUE"

It seems, that the zero is aligned to the right, instead of centered, and R is believing that the "zero" has the same amount of digits than the other big numbers (e.g. "100 000") and it aligns "000 000" centred instead of only "0".

Anything easy I can do?

Minimal Working Example:

plot(x=NULL, y=NULL, xlab="xlab", ylab="ylab"
, xlim=range(2007:2014), ylim=range(0:500000), axes=FALSE)
ticks_x <- pretty(2007:2014,n=6)
ticks_y <- pretty(0:500000,n=8)

labels_x <- format(ticks_x)
labels_y <- format(ticks_y , big.mark = " " , decimal.mark=",", scientific=FALSE)

axis(1, at = ticks_x, labels = labels_x)
axis(2, at = ticks_y, labels = labels_y)


enter image description here

enter image description here

Any suggestions how to "centre" the "zero", if no scientific-mode is used?

A manual solution with "inserting as text" or similar is not possible, because the plot is created inside a loop, and only sometimes the zero occurs, but then it is always wrong aligned.

Thanks a lot!

Answer Source

Axis labels are character strings. Have a check at your current labels_y:

#[1] "      0" " 50 000" "100 000" "150 000" "200 000" "250 000" "300 000"
#[8] "350 000" "400 000" "450 000" "500 000"

You get the undesired alignment, simply because the labels for 0 is " 0". The problem can be fixed by:

labels_y[1] <- "   0   "
## or simply: labels_y[1] <- "0"
axis(2, at = ticks_y, labels = labels_y)

enter image description here