54

I have eliminated labels on the y axis because only the relative amount is really important.

w <- c(34170,24911,20323,14290,9605,7803,7113,6031,5140,4469)
plot(1:length(w), w, type="b", xlab="Number of clusters",
     ylab="Within-cluster variance",
     main="K=5 eliminates most of the within-cluster variance",
     cex.main=1.5,
     cex.lab=1.2,
     font.main=20,
     yaxt='n',lab=c(length(w),5,7), # no ticks on y axis, all ticks on x
     family="Calibri Light")

cluster plot

However, suppressing those tick labels leaves a lot of white space between the y axis label ("Within-cluster variance") and the y axis. Is there a way to nudge it back over? If I somehow set the (invisible) tick labels to go inside the axis, would the axis label settles along the axis?

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
  • 3
    Try leaving `ylab` out of `plot` and putting it in `axis` instead with some placing option. (Can't recall the options offhand.) I.e., `plot(...); axis(2, ...)` – Alex A. May 15 '15 at 17:49

2 Answers2

67

Try setting ylab="" in your plot call and use title to set the label of the y-axis manually. Using line you could adjust the position of the label, e.g.:

plot(1:length(w), w, type="b", xlab="Number of clusters", ylab="",
     main="K=5 eliminates most of the within-cluster variance",
     cex.main=1.5,
     cex.lab=1.2,
     font.main=20,
     yaxt='n',lab=c(length(w),5,7), # no ticks on y axis, all ticks on x
     family="Calibri Light")

title(ylab="Within-cluster variance", line=0, cex.lab=1.2, family="Calibri Light")

enter image description here

Please read ?title for more details.

sgibb
  • 25,396
  • 3
  • 68
  • 74
  • 4
    Ah man, I was just about to post this exact thing. I had it all written out but I was trying to figure out why R on Windows wasn't letting me change the font. Anyway, nice work. – Alex A. May 15 '15 at 18:06
  • @sgibb thank you very much for teaching me that `title` can be used for labels (not just to set `main`). I wound up using two `title` statements, one to offset `ylab` by `line=1` and one to get `xlab` a little closer at `line=2.2`. Much appreciated. – C8H10N4O2 May 15 '15 at 18:13
39

Adjust mgp, see ?par

title(ylab="Within-cluster variance", mgp=c(1,1,0), family="Calibri Light",cex.lab=1.2)

enter image description here

xb.
  • 1,617
  • 11
  • 16
  • 5
    To move the axis title closer adjust `mgp[1]`. The default is 3. – qwr Nov 23 '19 at 00:17
  • More detail setting can be done by adjusting `mgp` parameters. `mgp=c(3,1,0)` generally set 3 objects, which are: A) `title` margin line for the axis title (default 3), B) `labels` margin line for the axis labels (default 1) , C) `line` margin line for the axis line (default 0). Thanks – Santosa Sandy Dec 18 '20 at 17:06