Find optimal width for left margin in R plot
label, plot, r, width
Solution
You can use `mai` instead of `mar` to specify a distance in inches (instead of "lines").
par(mai = c(1, strwidth(label, units="inches")+.25, .8, .2))
plot(1:2, axes=FALSE)
axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0)
You can compute the conversion factor between lines and inches by dividing `mar` by `mai`.
inches_to_lines <- ( par("mar") / par("mai") )[1] # 5
lab.width <- strwidth(label, units="inches") * inches_to_lines
par(mar = c(5, 1 + lab.width, 4, 2) + 0.1)
plot(1:2, axes=FALSE)
axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0)
Problem
I would like to write a plot function for my specific purposes and put the y labels on the left margin. The length of these labels, however, can differ dramatically and depends on the model terms the user comes up with. For this reason, I would like to measure the width of the longest label and set the left margin width accordingly. I found the `strwidth` function, but I don't understand how to convert its output unit to the unit of the `mar` argument. An example: ``` label <- paste(letters, collapse = " ") # create a long label par(mar = c(5, 17, 4, 2) + 0.1) # 17 is the left margin width plot(1:2, axes = FALSE, type = "n") # stupid plot example # if we now draw the axis label, 17 seems to be a good value: axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0) # however, strwidth returns 0.59, which is much less... lab.width <- strwidth(label) # so how can I convert the units? ```